关于JDK12新特性预览链接如下。
https://www.oschina.net/news/103411/jdk12-new-jep-list
本文重点对JDK 12中其中一个特性,对switch进行扩展,使其可以用作语句或表达式,简化日常代码。
例子1:作为语句时的用法
以前的写法:
private static void print(int day) {
switch (day) {
case 1:
case 2:
case 3:
System.out.println(6);
break;
case 4:
System.out.println(7);
break;
case 5:
case 6:
System.out.println(8);
break;
case 7:
System.out.println(9);
break;
}
}
新的语法:
private static void newPrint(int day) {
switch (day) {
case 1,2,3 -> System.out.println(6);
case 4 -> System.out.println(7);
case 5,6 -> System.out.println(8);
case 7 -> System.out.println(9);
}
}
如果需要在case后面执行多条语句
case 1,2,3 -> {
System.out.println(6);
System.out.println(7);
}
用例2:作为表达式时的用法
以前的写法:
private static int getDay(int day) {
int res = 0;
switch (day) {
case 1:
case 2:
case 3:
res = 6;
break;
case 4:
res = 7;
break;
case 5:
case 6:
res = 8;
break;
case 7:
res = 9;
break;
}
return res;
}
新的写法:
private static int getNewDay(int day) {
int res = switch (day) {
// case 1,2,3 -> 6;
case 1,2,3 -> {
break 6;
}
// 上面两种写法是等价的,上面那种写法其实是省略了break
case 4 -> 7;
case 5,6 -> 8;
case 7 -> 9;
default -> 0;
};
return res;
}
其中
case 1,2,3 -> 6;
// 等价于下面的,上面的写法是省略了break,注意是break,不是return
case 1,2,3 -> {
break 6;
}
还有一点需要注意的是,switch作为表达式时,要求必须要有返回值。
在上面的例子中,如果删除 default -> 0
这个将会报错。
Error:(66, 23) java: switch 表达式不包含所有可能的输入值
当前,如果case后面需要执行多条语句后返回值,则可以如下面的写法。break
后面加返回值。
case 1,2,3 -> {
System.out.println(1);
System.out.println(2);
System.out.println(3);
break 6;
}
关于Java 12中对switch的加强就这些了,比较简单,希望大家学习顺利。
笔者用的IDE是IDEA 2019.1版本的,语言 Level需要选择12(Preview) Switch Expression。
相关链接:
网友评论