I'm trying to declare an enum in Java and use a variable of that type in a switch statement, where all possible cases for enum constants of that type are covered.
enum MyEnum {
FOO,
BAR
}
private static void test(MyEnum e) {
String msg;
switch (e) {
case FOO:
msg = "foo";
break;
case BAR:
msg = "bar";
break;
}
System.out.println("Enum is: " + e + " msg is: " + msg); //compiler error
}
Why is the compiler not capable of detecting that this switch will always initialize msg
(or throw a NullPointerException because e
is null
)?
Imagine if MyEnum
was a separate class. Then it would be possible to recompile the MyEnum
class, and add new values, without recompiling EnumSwitchTest
(so not getting any errors).
Then it would be possible for another class to call test
with the new value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With