Guarded patterns with when
Add conditions to pattern cases using when guards.
Porównanie kodu
✕ 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ć.
Dlaczego nowoczesne podejście wygrywa
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
Wsparcie JDK
Guarded patterns with when
Dostępne
Widely available since JDK 21 LTS (Sept 2023)
Jak to działa
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.
Powiązana dokumentacja