Details
-
Type:
Sub-task
-
Status:
Closed
-
Priority:
Minor
-
Resolution: Fixed
-
Affects Version/s: None
-
Fix Version/s: 1.7-rc-1
-
Component/s: None
-
Labels:None
-
Testcase included:yes
-
Number of attachments :
Description
Java enum allows instance (value) specific methods. Groovy does not support this currently. The following code fails in Groovy (compilation error):
class GroovyEnumRangeTest extends GroovyTestCase {
void testEnumMethod()
}
enum Day {
SUNDAY {
String activity() { 'Relax' }
}, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
String activity() { 'Work' }
}
If I need it right now, I am able to use EMC to achieve this:
class GroovyEnumRangeTest extends GroovyTestCase
{
void testEnumMethod()
{
def emc = new ExpandoMetaClass(Day)
emc.activity = {-> 'Relax' }
emc.initialize()
Day.SUNDAY.metaClass = emc
assertEquals "Work", Day.MONDAY.activity()
assertEquals "Relax", Day.SUNDAY.activity()
assertEquals "Work", Day.TUESDAY.activity()
}
}
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
String activity() { 'Work' }
}
so it is not major (IMHO).
Attachments
Issue Links
| This issue is duplicated by: | ||||
| GROOVY-3178 | Dont support method override in enum |
|
|
|
| GROOVY-3408 | Groovy does not support abstract methods in enums |
|
|
|
| This issue depends upon: | ||||
| GROOVY-69 | support inner classes (or at least nested classes) |
|
|
|
The documentation suggests that this isn't a useful feature. Here's an example where I'm using it in Java, but can't port directly to Groovy. I wrote a lexer where I use enums as the token definitions, each with its own regex passed to the constructor. Each enum has its own onMatch method to do something specific with the regex capture groups.
Another workaround instead of ExpandoMetaClass is to pass a closure with an explicit this parameter, and curry it with the instance's this parameter which is visible in the constructor
enum Foo { Add(1, {_this, y -> _this.x + y }), Mult(100, {_this, y -> _this.x * y }) Foo(int x, Closure c) { this.x = x func = c.curry(this) } final Closure func int x } import static Foo.* println Add.func(10) println Mult.func(10)enum Foo { Add(1, {_this, y -> _this.x + y }), Mult(100, {_this, y -> _this.x * y }) Foo(int x, Closure c) { this.x = x func = c.curry(this) } final Closure func int x } import static Foo.* println Add.func(10) println Mult.func(10)