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";
};
このコードに問題がありますか? お知らせください。
🎯

精密なマッチング

型と条件を1つのcaseラベルで組み合わせられます。

📐

フラットな構造

switchのcase内にif/elseをネストする必要がありません。

📖

読みやすい意図

when句は自然な言葉のように読めます。

旧来のアプローチ
ネストしたif
モダンなアプローチ
when句
JDKバージョン
21
難易度
中級
whenによるガード付きパターン
利用可能

JDK 21 LTS(2023年9月)以降、広く利用可能

ガード付きパターンを使うと、型マッチングに追加のboolean条件を付け加えられます。これにより、すべての分岐ロジックをswitch内に収められ、case内にif文をネストする必要がなくなります。

共有 𝕏 🦋 in