Why is default required for a switch on an enum?

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

    In Java 12 you can use the preview switch expression feature (JEP-325) as follows:

    public static String testSwitch(XYZ xyz) {
        return switch (xyz) {
            case A -> "A";
            case B -> "B";
        };
    }
    

    and you don't need default case as long as you handle all enum values in switch.

    Note, to use a preview feature you'll have to pass --enable-preview --source 12 options to javac and java

提交回复
热议问题