在Java 12中,对switch
语句进行了增强,以便可以将其用作表达式。 现在也可以在一种情况下打开多个常量,从而使代码更简洁易读。 这些增强是预览语言功能 ,这意味着必须使用--enable-preview
标志在Java编译器和运行时中显式启用它们。
考虑以下switch
语句:
int result = - 1 ; switch (input) { case 0 : case 1 : result = 1 ; break ; case 2 : result = 4 ; break ; case 3 : System.out.println( "Calculating: " + input); result = compute(input); System.out.println( "Result: " + result); break ; default : throw new IllegalArgumentException( "Invalid input " + input); }
在Java 12中,可以使用switch
表达式将其重写,如下所示:
final int result = switch (input) { case 0 , 1 -> 1 ; case 2 -> 4 ; case 3 -> { System.out.println( "Calculating: " + input); final int output = compute(input); System.out.println( "Result: " + output); break output; } default -> throw new IllegalArgumentException( "Invalid input " + input); };
如上图所示:
- 在表达式中使用该
switch
为result
整数分配一个值 - 在单个
case
有多个标签用逗号分隔 - 新的
case X ->
语法没有任何缺陷。 仅执行箭头右边的表达式或语句 -
break
语句接受一个参数,该参数成为switch
表达式返回的值(类似于return
)
翻译自: https://www.javacodegeeks.com/2019/06/java-12-switch-expressions.html