java14对switch表达式进行了增强,下面我们来演示几种用法。
使用lambda方式
使用lambda方式的箭头标签匹配时,箭头标签后面的语句后表达式会直接执行,不需要break
关键字。以前写switch
表达式时经常会漏写break
,导致产生许多不可预测的问题,以后再也不会担心了。
以下这个例子后面的语句会直接执行
public static void main(String[] args) {
printDigit(4);
}
private static void printDigit(int i){
switch (i){
case 1 -> System.out.println("one");
case 2 -> System.out.println("tow");
case 3 -> System.out.println("three");
case 4,5,6 -> System.out.println("four,five or six");
default -> System.out.println("big digit");
}
}
four,five or six
以下的例子会返回后面的表达式。
public static void main(String[] args) {
System.out.println(getDigit(5));
}
private static String getDigit(int i){
return switch (i){
case 1 -> "one";
case 2 -> "tow";
case 3 -> "three";
case 4,5,6 -> "four,five or six";
default -> "big digit";
};
}
four,five or six
yield关键字
当使用lambda方式,箭头标签后是一个复杂的语句块时,可以需要使用yield
进行返回。yield
和return
的区别是,return
会跳出当前的方法,yield
只会跳出当前的switch
块。
public static void main(String[] args) {
getDigit(5);
}
private static void getDigit(int i){
String printDigit = switch (i){
case 1 -> "one";
case 2 -> "tow";
case 3 -> "three";
case 4,5,6 -> {
if (i % 2 ==0) {
yield "even";
} else {
yield "odd";
}
}
default -> "big digit";
};
System.out.println(printDigit);
}
odd