frangulyan
frangulyan

Reputation: 3847

Java switch statement get to default on enum

I have a Java (for Android) code similar to this one:

enum MyEnum {
    A, B, C
} 

String f(MyEnum e) {
    if (e == null) {
        return null;
    }

    switch(e) {
        case A: return "AA";
        case B: return "BB";
        case C: return "CC";
        default: throw new IllegalStateException("invalid enum");
    }
}

and I got the exception in the default clause thrown once! Can somebody explain if this is theoretically possible and how?

For example in C++ you can have an enum variable which value is non of the declared enum values, but I guess in Java you cannot do that, correct me if I am wrong.

Upvotes: 0

Views: 315

Answers (1)

Pienterekaak
Pienterekaak

Reputation: 456

I dont see how this could fail, but i would propose refactoring your enum to this:

enum MyEnum {
  A("AA"),
  B("BB"), 
  C("CC");

  private final String value;  

  public MyEnum(String value){
    this.value = value;
  }

  public String f(){
    return value;
  }
}

now you can still do the same operations, but it 100% safe to add new enums

public void foo(MyEnum enum){
  System.out.println(enum.f());
}

Upvotes: 1

Related Questions