引入了yield语句,用于返回值;

和return的区别在于:return会直接跳出当前循环或者方法,而yield只会跳出当前switch块。

@Test
public void testSwitch2(){
    String x = "3";
    int i = switch (x) {
        case "1" -> 1;
        case "2" -> 2;
        default -> {
        	yield 3;
        }
    };
    System.out.println(i);
}
@Test
public void testSwitch3() {
    String x = "3";
    int i = switch (x) {
        case "1":
        yield 1;
        case "2":
        yield 2;
        default:
        yield 3;
    };
    System.out.println(i);
}

相关文章:

  • 2021-10-05
  • 2022-01-21
  • 2021-11-05
  • 2021-06-20
  • 2021-06-24
  • 2022-02-06
  • 2021-09-12
  • 2022-12-23
猜你喜欢
  • 2021-05-16
  • 2021-07-03
  • 2022-12-23
  • 2022-12-23
  • 2021-05-23
  • 2021-08-01
  • 2021-12-17
相关资源
相似解决方案