您可能还记得我以前的文章,在Java 12中,传统的switch
语句得到了增强,因此可以用作表达式。 在Java 13中,对该功能进行了进一步的更改 。 break
语句不再可以返回值。 相反,您必须使用新的yield
语句,如下所示:
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); yield output; } default -> throw new IllegalArgumentException( "Invalid input " + input); };
请注意,这仍然是预览语言功能 ,这意味着必须使用--enable-preview
标志在Java编译器和运行时中显式启用它。
翻译自: https://www.javacodegeeks.com/2019/11/java-13-enhancements-to-switch-expressions.html