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