jdk12switch表达式

1.传统switch弊端
jdk12switch表达式_jdk
2.何为预览语言
jdk12switch表达式_jdk_02
3.语法详解
jdk12switch表达式_java_03
4.代码举例
java12之前

/**
* @author shkstart
* @create 2019 下午 4:47
*/
public class SwitchTest {
  public static void main(String[] args) {
    int numberOfLetters;
    Fruit fruit = Fruit.APPLE;
    switch (fruit) {
      case PEAR:
        numberOfLetters = 4;
        break;
      case APPLE:
      case GRAPE:
      case MANGO:
        numberOfLetters = 5;
        break;
      case ORANGE:
      case PAPAYA:
        numberOfLetters = 6;
        break;
      default:
        throw new IllegalStateException("No Such Fruit:" + fruit);
   }
    System.out.println(numberOfLetters);
 }
}
enum Fruit {
  PEAR, APPLE, GRAPE, MANGO, ORANGE, PAPAYA;
}

如果有编码经验,你一定知道,switch 语句如果漏写了一个break,那么逻辑往往就跑偏了,这种方式既繁琐,又容易出错。如果换成 switch 表达式,Pattern Matching 机制能够自然地保证只有单一路径会被执行:
Java 12

/**
* @author shkstart
* @create 2019 下午 10:38
*/
public class SwitchTest1 {
  public static void main(String[] args) {
    Fruit fruit = Fruit.GRAPE;
    switch(fruit){
      case PEAR -> System.out.println(4);
      case APPLE,MANGO,GRAPE -> System.out.println(5);
      case ORANGE,PAPAYA -> System.out.println(6);
      default -> throw new IllegalStateException("No Such Fruit:" + fruit);
   };
 }
}

更进一步,下面的表达式,为我们提供了优雅地表达特定场合计算逻辑的方式:

/**
* @author shkstart
* @create 2019 下午 10:44
*/
public class SwitchTest2 {
  public static void main(String[] args) {
    Fruit fruit = Fruit.GRAPE;
    int numberOfLetters = switch(fruit){
      case PEAR -> 4;
      case APPLE,MANGO,GRAPE -> 5;
      case ORANGE,PAPAYA -> 6;
      default -> throw new IllegalStateException("No Such Fruit:" + fruit);
   };
    System.out.println(numberOfLetters);
 }
}

5.使用总结
jdk12switch表达式_java_04
6.展望
jdk12switch表达式_switch_05