Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java require a dead return statement after a fully-covered enum?

Even though it's impossible to get passed the switch statement, I am still required to include a return statement. Enums can't be extended so it's impossible to add or remove other values in the future.

Is this a bug in Java? If not, do you know why this is?

Here is an example to see what I mean:

public class Example{

    enum Day{
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }

    public static String getType(Day day, boolean weekendOff){

        switch(day){
            case Monday:
            case Tuesday:
            case Wednesday:
            case Thursday:
                return "work day";
            case Friday:
            case Saturday:
            case Sunday:
                if (weekendOff){
                    return "party day";
                }
                else {
                    return "work day";
                }
        }

        //this is the line I don't understand
        return "";


    }

     public static void main(String []args){

         getType(Day.Monday, false);

     }
}
like image 335
Jason Avatar asked Sep 27 '26 23:09

Jason


1 Answers

Because it's possible for new enum elements to be added in future. If your enum-using class doesn't get recompiled, then your code would no longer be correct. This heads off that possibility.

As everybody else has said, just add a default clause to deal with that case, probably by throwing an AssertionError.

like image 53
Chris Jester-Young Avatar answered Sep 29 '26 12:09

Chris Jester-Young



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!