Why is default required for a switch on an enum?

后端 未结 8 2064
礼貌的吻别
礼貌的吻别 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:41

    As has been stated, you need to return a value and the compiler doesn't assume that the enum cannot change in the future. E.g. you can create another version of the enum and use that without recompiling the method.

    Note: there is a third value for xyz which is null.

    public static String testSwitch(XYZ xyz) {
        if(xyz == null) return "null";
        switch(xyz){
        case A:
            return "A";
        case B:
            return "B";
        }
        return xyz.getName();
    }
    

    This ha the same result as

    public static String testSwitch(XYZ xyz) {
         return "" + xyz;
    }
    

    The only way to avoid a return is to throw an exception.

    public static String testSwitch(XYZ xyz) {
        switch(xyz){
        case A:
            return "A";
        case B:
            return "B";
        }
        throw new AssertionError("Unknown XYZ "+xyz);
    }
    

提交回复
热议问题