9

I have a switch statement in Java, on an Enum which let us call IMyInterface.MyEnum

Each of my case statements has the form: IMyInterface.MyEnum.MyValue, (though I could drop the IMyInterface if I imported).

However, the compiler (Java 6) throws an error: "The qualified case label IMyInterface.MyEnum.MyValue must be replaced with the unqalified enum constant MyValue".

I can obviously do that, but for the life of me I don't understand what is the purpose of this error. Clearly, if the compiler can deal with the actual value, it should be able to deal with the fully qualified name just as it would for constants. In fact, I would have assumed that the compiler turns the constant into the fully qualified name.

So, Java gurus, what's the rationale behind this? Thank you!

Uri
  • 88,451
  • 51
  • 221
  • 321
  • 1
    Personally, I don't mind that enums can't be qualified in switch-case blocks; it makes the code more readable. Keep in mind that for enum classes that you own (in code you can edit), best practice is to never use a switch-case block. Enum constant-specific methods are more maintainable and less fragile than switch-case in this situation. – scottb Jan 07 '16 at 23:05

2 Answers2

18

From the JLS:

(One reason for requiring inlining of constants is that switch statements require constants on each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switch statement at compile time; the class file format does not do symbolic linkage of case values.)

You can find it here.

user4975679
  • 1,461
  • 16
  • 21
laginimaineb
  • 8,245
  • 1
  • 22
  • 14
3

That's an odd one. I had to do some digging myself to find out about this. It seems that it's safer to type check on the object being switched on than in the full qualified name.

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6191812 was a bug report raised to allow you to specify qualified enums but it was closed and not actioned for the reasons you can see in the enclosure.

NeilInglis
  • 3,431
  • 4
  • 30
  • 31