代码对比
✕ Java 8
if (shape instanceof Circle c) {
if (c.radius() > 10) {
return "large circle";
} else {
return "small circle";
}
} else {
return "not a circle";
}
✓ Java 21+
return switch (shape) {
case Circle c
when c.radius() > 10
-> "large circle";
case Circle c
-> "small circle";
default -> "not a circle";
};
发现此代码有问题? 告诉我们。
为什么现代方式更好
精确匹配
在单个 case 标签中组合类型和条件。
扁平结构
switch case 内无嵌套 if/else。
可读意图
when 子句读起来像自然语言。
旧方式
嵌套 if
现代方式
when 子句
自 JDK
21
难度
中级
JDK 支持
带 when 的守卫模式
可用
自 JDK 21 LTS 起广泛可用(2023 年 9 月)
工作原理
守卫模式让您使用 when 关键字通过额外的布尔条件来细化类型匹配。这替代了 switch 分支内的嵌套 if/else。
相关文档