引入了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); }