Why must enum constants be unqualified in switch cases in java?

2k views Asked by At

A bit of context. This is about the Problem with qualified enum names in switch cases like in the example:

enum MyEnum {
    A,
    B,
    ;
}
switch(methodReturnungMyEnum()){
case MyEnum.A:
    // ...
    break
case MyEnum.B:
    // ...
    break
}

which yields the compiler error

An enum switch case label must be the unqualified name of an enumeration constant

Yeah. The solution is simple: Remove MyEnum. part. Thats not my question.

I was simply wondering why this is forbidden in the first place. I know that it is basically impossible to definitely answer why something was done in a certain way. Instead i want to ask for reasons that might have caused this decision. In what way are qualified and unqualified enum constants (or maybe symbols in general) different? And what could go wrong if the compiler would allow this anyway?

While there exists quite a few questions on how to fix the compiler error itself nobody seems to address above questions.

1

There are 1 answers

1
josejuan On BEST ANSWER

The real enumeration type is defined into the switch sentence then, for every case clause the compiler only must to check the literal exists into that enumeration.

If you allow to specify the qualified (full qualified, etc...) in the case clause then, the compiler must to perform a useless step (check that symbol is a member of the given enumeration).

That is the reason why it is not the same to put it as not (which is what it might seem at first).

Technically that restriction is responsed here and explained here.