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");
Written by Ashwin
Related protips
3 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Groovy
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#