Why is default required for a switch on an enum?

后端 未结 8 2086
礼貌的吻别
礼貌的吻别 2020-11-29 08:46

Normally, default is not necessary in a switch statement. However, in the following situation the code successfully compiles only when I uncomment the default statement. Can

8条回答
  •  孤街浪徒
    2020-11-29 09:46

    There is a contract that this method has to return a String unless it throws an Exception. And everytime is not limited to those cases where the value of xyz is equal to XVZ.A or XYZ.B.

    Here's another example, where it's obviuos, that the code will run correct but where we have a compiletime error for the very same reason:

    public boolean getTrue() {
      if (1 == 1) return true;
    }
    

    It is not true that you have to add a default statement, it is true, that you have to return a value at any time. So either add a default statement or add a return statement after the switch block.

提交回复
热议问题