switch
Switch 增强的三个方面,参考:JEP 361
- 支持箭头表达式
- 支持 yied 返回值
- 支持 Java Record
箭头表达式 & 新的 case 标签
Switch 新语法示例:
public static void main(String[] args) {
int week = 7;
String memo = "";
switch (week){
case 1 -> memo = "星期日,休息";
case 2, 3, 4, 5, 6 -> memo = "工作日";
case 7 -> memo = "星期六,休息";
default -> throw new IllegalArgumentException("无效的日期:");
}
System.out.println("week = " + memo);
}
yeild 返回值
yeild 让 switch 作为表达式,能够返回值.
yield 返回值,跳出 switch 块示例:
public static void main(String[] args) {
int week = 2;
// yield 是 switch 的返回值, yield 跳出当前 switch 块:
String memo = switch (week) {
case 1: yield "星期日,休息";
case 2, 3, 4, 5, 6: yield "工作日";
case 7: yield "星期六,休息";
default: yield "无效日期";
};
System.out.println("week = " + memo);
}
多表达式,case 与 yield 结合使用示例:
public static void main(String[] args) {
int week = 1;
//yield 是 switch 的返回值, yield 跳出当前 switch 块:
String memo = switch (week) {
case 1 -> {
System.out.println("week=1 的 表达式部分");
yield "星期日,休息";
}
case 2, 3, 4, 5, 6 -> {
System.out.println("week=2,3,4,5,6 的 表达式部分");
yield "工作日";
}
case 7 -> {
System.out.println("week=7 的 表达式部分");
yield "星期六,休息";
}
default -> {
System.out.println("其他语句");
yield "无效日期";
}
};
System.out.println("week = " + memo);
}
提示:
case 标签 -> 与 case 标签:不能混用。一个 switch 语句块中使用一种语法格式。switch 作为表达式,赋值给变量,需要 yield 或者 case 标签 -> 表达式。-> 右侧表达式为 case 返回值。
示例:
```java
public static void main(String[] args) {
int week = 1;
// yield 是 switch 的返回值, yield 跳出当前 switch 块:
String memo = switch (week) {
case 1 -> {
System.out.println("week=1 的 表达式部分");
yield "星期日,休息";
}
case 2, 3, 4, 5, 6 -> {
System.out.println("week=2,3,4,5,6 的 表达式部分");
yield "工作日";
}
case 7 -> "星期六,休息";
default -> "无效日期";
};
System.out.println("week = " + memo);
}
# 使用 Record
switch 表达式中使用 record ,结合 case 标签 -> 表达式,yield 实现复杂的计算。
1. 准备三个 Record
```java
public record Line(int x,int y) {}
public record Rectangle(int width,int height) {}
public record Shape(int width,int height) {}
- switch record
public static void main(String[] args) {
Line line = new Line(10, 100);
Rectangle rectangle = new Rectangle(100, 200);
Shape shape = new Shape(200, 200);
Object obj = rectangle;
int result = switch (obj) {
case Line(int x, int y) -> {
System.out.println("图形是线, X:" + x + ",Y:" + y);
yield x + y;
}
case Rectangle(int w, int h) -> w * h;
case Shape(int w, int h) -> {
System.out.println("这是图形,要计算周长");
yield 2 * (w + h);
}
default -> throw new IllegalStateException("无效的对象:" + obj);
};
System.out.println("result = " + result);
}

浙公网安备 33010602011771号