Language Średniozaawansowany

Add conditions to pattern cases using when guards.

✕ 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";
};
Widzisz problem z tym kodem? Daj nam znać.
🎯

Precise matching

Combine type + condition in a single case label.

📐

Flat structure

No nested if/else inside switch cases.

📖

Readable intent

The when clause reads like natural language.

Stare podejście
Nested if
Nowoczesne podejście
when Clause
Od JDK
21
Poziom trudności
Średniozaawansowany
Guarded patterns with when
Dostępne

Widely available since JDK 21 LTS (Sept 2023)

Guarded patterns let you refine a type match with an additional boolean condition. This keeps all the branching logic in the switch instead of nesting if statements inside cases.

Udostępnij 𝕏 🦋 in