Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error - switch with enum [duplicate]

Possible Duplicate:
Why do I get an Enum constant reference cannot be qualified in a case label?

Hi, Does someone knows why when I switch over an Enum, the cases should be on the unqualified Enum value?

Example:

switch(var) {

case Enum.FIRST:

break;

}

is illegal

but:

switch(var) {

case FIRST:

break;

}

is legal.

I understand that var is of a specific type (Enum) but why the compiler cares if I use the fully qualified name of the Enum value?

like image 953
gads Avatar asked Apr 05 '11 12:04

gads


2 Answers

Because the Java Language Specification states that it is so.

Specifically, the defintition of a SwitchLabel:

SwitchLabel:
        case ConstantExpression :
        case EnumConstantName :
        default :

See http://java.sun.com/docs/books/jls/third_edition/html/statements.html#258896

like image 158
developmentalinsanity Avatar answered Oct 15 '22 14:10

developmentalinsanity


I'm guessing because otherwise you could do something like this:

switch(var) {
  case AnyOtherEnum.FIRST:
  break;
}
like image 25
Lukas Eder Avatar answered Oct 15 '22 14:10

Lukas Eder