Last active
December 20, 2015 18:19
-
-
Save msakamoto-sf/6175058 to your computer and use it in GitHub Desktop.
Groovy and enum demo. Groovy 1.8.9 doesn't suport enum's abstract method, but static initializer and metaClass makes nealy likely enable it.
This is a work arround for http://jira.codehaus.org/browse/GROOVY-4641
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tested on Groovy 1.8.9. | |
enum GreetEnum { | |
MORNING("Good Morning"), | |
AFTERNOON("Good Afternoon"), | |
EVENING("Good Evening"); | |
static { | |
MORNING.metaClass.greeting = { String you -> | |
return delegate.emphasize() + " " + you + ", I'm sleeping..." | |
} | |
AFTERNOON.metaClass.greeting = { String you -> | |
return delegate.greet + " " + you + ", let's coffee break!" | |
} | |
} | |
String greet | |
GreetEnum(String _greet) { | |
this.greet = _greet | |
} | |
String greeting(String you) { | |
throw new UnsupportedOperationException() | |
} | |
String emphasize() { | |
return this.greet + "!!" | |
} | |
} | |
assert GreetEnum.MORNING.greeting("abc") == "Good Morning!! abc, I'm sleeping..." | |
assert GreetEnum.AFTERNOON.greeting("abc") == "Good Afternoon abc, let's coffee break!" | |
//Caught: java.lang.UnsupportedOperationException | |
//assert GreetEnum.EVENING.greeting("abc") == "Good Evening abc" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment