I want to avoid creating a switch case and instead use an enum
but when writing the following code, I get a compile error saying unexpected token public
:
public enum Status {
INACTIVE {
public void doSomething() {
//do something
}
},
ACTIVE {
public void doSomething() {
//do something else
}
},
UNKNOWN {
public void doSomething() {
//do something totally different
}
};
public abstract void doSomething()
}
Basically what I want to achieve is something similar to this:
public enum Status {
ACTIVE,
INACTIVE,
UNKNOWN;
}
switch (getState()) {
case INACTIVE:
//do something
break;
case ACTIVE:
//do something else
break;
case UNKNOWN:
//do something totally different
break;
}
Is this allowed in Gosu? How should I go about achieving such a behavior?
You have miss-understood the concept of Enum
. First of all, enum
is inherited from java.lang.Enum
. It's not allowed to implement inner classes to Enum constants
. You have to consider ACTIVE,INACTIVE and UNKNOWN (Enum constants
) as objects
of class type
Status.
Proof:
Status.ACTIVE.getClass()
== class Status
Status.ACTIVE instanceof Status
== true
Status.ACTIVE instanceof java.lang.Enum
== true
If you want to avoid the switch
statement in your main code, you can move the switch
into the implementation of enum
as follows; (coded in Gosu)
enum Status {
ACTIVE,INACTIVE,UNKNOWN;
public function doSomething(){
switch (this) {
case INACTIVE:
//do something
break;
case ACTIVE:
//do something
break;
case UNKNOWN:
//do something
break;
}
}
}
Now you have the capability to call the doSomething()
method from the enum constants
in your main code
Example:
var a=Status.ACTIVE
var b=Status.INACTIVE
var c=Status.UNKNOWN
a.doSomething()
b.doSomething()
c.doSomething()