Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why, when I have cases for every enum constant in a switch statement, must I still provide a default? [duplicate]

Tags:

java

enums

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)?

like image 237
dosw Avatar asked Jul 03 '15 12:07

dosw


1 Answers

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.

like image 85
user253751 Avatar answered Oct 07 '22 23:10

user253751