2

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?

forgetaboutme
  • 613
  • 1
  • 6
  • 18

2 Answers2

3

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()
madup
  • 66
  • 3
2

As you can read in Gosu grammar or below function is not allowed inside enum consts, even brackets {} after consts are not allowed.

What is allowed in enum body:

enumBody = "{" [enumConstants] classMembers "}" .
enumConstants = enumConstant {"," enumConstant} [","] [";"] .
enumConstant = {annotation} id optionalArguments .

So basically in GOSU enum contains consts and rest normally as in any other class.

kajojeq
  • 886
  • 9
  • 27