I have a function that switch
es on a value of some enum type, and in all cases returns a value. However, the Java compiler is not happy with this function unless it also returns a default value. A minimal example is as follows:
class Main {
enum MyEnum {
A,
B
}
static String toString(MyEnum e) {
switch (e) {
case A: return "A";
case B: return "B";
}
// COMPILER COMPLAINS HERE: 'MISSING RETURN STATEMENT'
}
public static void main(String[] args) {
System.out.println(toString(MyEnum.A) + toString(MyEnum.B));
}
}
Adding either a default
case in the switch
, or simply returning a default value at the end of the function, now allows the code to compile:
// only 1 of the 2 fixes is required to get this to compile
static String toString(MyEnum e) {
switch (e) {
case A: return "A";
case B: return "B";
default: return null; // fix 1
}
return null; // fix 2
}
Why is this the case? As I understand it, enums in Java are type-safe so cannot contain unexpected values (whereas in say, C or C++, you could force in a random integer into a function that takes an enum type and really cause problems). As a result the code without a default feels like it should work, but clearly the Java compiler isn't happy about it. Does anybody have information on what about the Java language causes this to be the case?