Last Updated: February 25, 2016
· winash

Groovy - delegation using enums and closures

Groovy puts the fun back into Java, here is one of the tricks I use to delegate actions based on enum values.

enum Super {

BATMAN({arg1 ->
    println "I live in $arg1 city"
SUPERMAN({arg1 ->
    println "I was born in  $arg1"
SHAKTIMAN({arg1 ->
    println "I live in $arg1 city"

Closure cl

Super(Closure cl) { = cl

def address(def arg){

you can now call the method address on this enum.


3 Responses
Add your response

Why have the extra method for address? Just rename c1 to address.

over 1 year ago ·

Java legacy I guess, the cl was private in my head :)

over 1 year ago ·

You could remove constructor by using : groovy.transform.TupleConstructor

enum Super {...

over 1 year ago ·