文章目录
Switch
JDK12后,switch语句升级写法:
private static String createPlayer(PlayerTypes playerType) {
return switch (playerType) {
case TENNIS -> "网球运动员费德勒";
case BASKETBALL,FOOTBALL -> "篮球运动员詹姆斯";
case UNKNOWN -> throw new IllegalArgumentException("未知");
};
}
像Lambda一样,右侧可使用{}将代码括起来
private static String createPlayer(PlayerTypes playerType) {
return switch (playerType) {
case PINGPANG -> {
System.out.println("乒乓球");
yield "乒乓球运动员马龙";
}
case UNKNOWN -> throw new IllegalArgumentException("未知");
};
}
编译器在生成字节码的时候对 yield 关键字做了自动化转义,转成了传统的 break 语句;