Last Updated: February 25, 2016
·
3.562K
· 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) {
   this.cl = cl
}

def address(def arg){
    return cl.call(arg)
}
}

you can now call the method address on this enum.

Super.SUPERMAN.address("Krypton");
Super.BATMAN.address("Gotham");

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

@TupleConstructor
enum Super {...
}

over 1 year ago ·