Guarded patterns with when
Code Comparison
if (shape instanceof Circle) {
Circle c = (Circle) shape;
if (c.radius() > 10) {
return "large circle";
} else {
return "small circle";
}
} else {
return "not a circle";
}
return switch (shape) {
case Circle c
when c.radius() > 10
-> "large circle";
case Circle c
-> "small circle";
default -> "not a circle";
};
Why the modern way wins
๐ฏ
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.
Modern Approach
when Clause
JDK Support
Guarded patterns with when
Available
Widely available since JDK 21 LTS (Sept 2023)
How it works
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.
Related Documentation
Proof