Java13新特性 -- switch表达式

引入了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);
}
posted @ 2019-11-12 20:19  西北野狼  阅读(1293)  评论(0编辑  收藏  举报