Language 中级

使用 when 守卫向模式 case 添加条件。

✕ 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
难度
中级
带 when 的守卫模式
可用

自 JDK 21 LTS 起广泛可用(2023 年 9 月)

守卫模式让您使用 when 关键字通过额外的布尔条件来细化类型匹配。这替代了 switch 分支内的嵌套 if/else。

分享 𝕏 🦋 in