Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java forcing default return statement from method with enum switch with all enum values covered

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:

  • de-serialization from I/O data - but then java.lang.IllegalArgumentException: No enum constant happen long before call to getMessageForType
  • possible null method parameter - but then it will fail on switch(myType) evaluation with java.lang.NullPointerException

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

like image 578
agienka Avatar asked Oct 24 '25 02:10

agienka


1 Answers

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();.

like image 154
Louis Wasserman Avatar answered Oct 25 '25 15:10

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!