yls43g
Last Updated: February 25, 2016
·
1.708K
· winash
F1f66bed667ae8b3a12a8ed813f65f8c

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");
Say Thanks
Respond

3 Responses
Add your response

813
9114304b96acd7b2bd88275eaccdbdbf

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

over 1 year ago ·
820
F1f66bed667ae8b3a12a8ed813f65f8c

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

over 1 year ago ·
2426
E1b2084f87c0bb3d6e5afa63cf00cccd

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

@TupleConstructor
enum Super {...
}

over 1 year ago ·