Switch 表达式
JDK 12
目前实现的特性:Switch Expressions (Preview)
Raw String Literals (Preview)
One AArch64 Port, Not Two
Default CDS Archives
非常遗憾模式匹配还是没赶上,而JEP 325: Switch Expressions (Preview)作为JEP 305: Pattern Matching的先导特性已经可以试用了.
$ /javac --version
javac 12-ea
Expression
顾名思义,现在的switch是表达式,他是有值的:
public class Test {
enum Alpha{
A,B,C,D,E
}
static char fun(Alpha alpha){
var r = switch (alpha){
case A -> 'a';
case B -> 'b';
case C -> 'c';
case D -> 'd';
};
return r;
}
public static void main(String[] args){
System.out.print(fun(Alpha.A));
}
}
Switch Expression目前还是预览特性,编译需要加上--enable-preview
$ javac --release 12 --enable-preview -Xlint:preview Test.java
Test.java:7: warning: [preview] switch expressions are a preview feature and may be removed in a future release.
var r = switch (alpha){
^
Test.java:8: warning: [preview] switch rules are a preview feature and may be removed in a future release.
case A -> 'a';
^
Test.java:9: warning: [preview] switch rules are a preview feature and may be removed in a future release.
case B -> 'b';
^
Test.java:10: warning: [preview] switch rules are a preview feature and may be removed in a future release.
case C -> 'c';
^
Test.java:11: warning: [preview] switch rules are a preview feature and may be removed in a future release.
case D -> 'd';
^
Test.java:7: error: the switch expression does not cover all possible input values
var r = switch (alpha){
^
1 error
5 warnings
可以看到,编译器目前可以检查是否写完整所有的"模式",虽然他还还不能告诉你哪里漏写了.
$ java --enable-preview Test
a%
你还可以换一种方式,在switch语句中用break返回switch表达式的值:
var r = switch (alpha){
case A :
break 'a';
case B :
break 'b';
case C :
break 'c';
case D :
break 'd';
case E :
break 'e';
};
编译:
javac --release 12 --enable-preview -Xlint:preview Test.java
Test.java:7: warning: [preview] switch expressions are a preview feature and may be removed in a future release.
var r = switch (alpha){
^
1 warning
这次警告要少一些,很神奇.
不过我还是认为 switch 代码块赋值给变量,后面还是要加上分号很奇怪.