I have the following example situation:
public void shouldReturnStringForEnum() {
MessageType myType = getType();
System.out.println(getMessageForType(myType));
}
String getMessageForType(MessageType myType) {
switch(myType) {
case error:
return "Error type";
case warning:
return "Warning type";
case info:
return "Info type";
}
} // <= error: missing return statement
MessageType getType() {
Random random = new Random();
return MessageType.values()[random.nextInt(3)];
}
enum MessageType {error, warning, info }
I can't figure out what is the possibility to return from method getMessageForType in other way than from the body of switch statement.
I was thinking about:
java.lang.IllegalArgumentException: No enum constant happen long before call to getMessageForTypeswitch(myType) evaluation with java.lang.NullPointerExceptionForcing a default return statement is uncomfortable in such situations, because I don't know what to return here. Throwing an exception in such case also has no sense here. What is the design decision behind such behaviour?
Please help, what am I missing here?
What happens if you edit the enum later, adding a new constant, without recompiling the switch? That's the case being guarded against.
It's perfectly normal to write default: throw new AssertionError();.
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