Sub topic 14
Pattern Matching for Switch and Record Patterns
In earlier chapters you used switch with enum constants, and you built a sealed interface whose subtypes are records. This chapter brings those two ideas together. You need JDK 21 or later to run the code.
What Pattern Matching Means
A pattern is a test plus a way to pull out data. When a value matches the pattern, Java gives you named variables that hold the parts you asked for.
Before Java 21, a switch could only compare a value against constants such as numbers, strings, or enum constants. Now a case can also check the type of a value. This is called a type pattern. A case can also take a record apart into its components. This is called a record pattern.
Type Patterns in a Switch
A type pattern looks like case Circle c. It means "if the value is a Circle, call it c and run this branch."
Record Patterns
A record pattern looks like case Square(double side). It checks that the value is a Square. Then it calls the accessor for you and stores the result in side. You skip the step of writing s.side().
You can write var instead of the component type, as in case Rectangle(var w, var h). Java works out the types for you.
A Complete Example
Save this as Main.java and run it with java Main.java.
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
public class Main {
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square(double side) -> side * side;
case Rectangle(var w, var h) -> w * h;
};
}
static String describe(Shape shape) {
return switch (shape) {
case Circle(double r) when r == 0 -> "a dot";
case Circle(double r) -> "a circle with radius " + r;
case Square s -> "a square";
case Rectangle(double w, double h) when w == h -> "a rectangle shaped like a square";
case Rectangle r -> "a rectangle";
};
}
public static void main(String[] args) {
Shape[] shapes = {
new Circle(0), new Circle(2), new Square(3),
new Rectangle(4, 4), new Rectangle(2, 5)
};
for (Shape s : shapes) {
System.out.printf("%s, area %.2f%n", describe(s), area(s));
}
}
}The output is:
a dot, area 0.00
a circle with radius 2.0, area 12.57
a square, area 9.00
a rectangle shaped like a square, area 16.00
a rectangle, area 10.00Guards with `when`
A guard is an extra condition added with when. The case matches only if the type fits and the condition is true. In describe, a Circle with radius 0 goes to the first branch. Every other circle goes to the second one.
Java checks cases from top to bottom, so put the guarded case first. If you put the plain case Circle(double r) above it, the guarded case could never run, and the compiler reports an error.
Why Sealed Types Make This Safe
A switch is exhaustive when it covers every possible value. Shape is sealed, so the compiler knows the only subtypes are Circle, Square, and Rectangle. That is why neither switch needs a default branch. Enums work the same way, because the compiler knows every constant.
This gives you a safety net. If someone adds a new shape later, every switch that forgot it stops compiling. You find the gap at compile time, not when a user hits it.
Summary
| Pattern | Example | What it gives you |
|---|---|---|
| Type pattern | `case Circle c` | The whole object as `c` |
| Record pattern | `case Square(double side)` | Each component as its own variable |
| Guarded pattern | `case Circle(double r) when r == 0` | A match only when the condition is true |
Exercise
You add record Triangle(double base, double height) implements Shape {} and list Triangle in the permits clause. You do not change area. What happens when you compile, and how do you fix it?
Show answer
The compiler reports an error because the switch in area no longer covers every possible Shape. To fix it, add a case such as case Triangle(double b, double h) -> 0.5 * b * h;. The switch in describe fails in the same way and also needs a Triangle case.
Exercise
Why does case Circle(double r) when r == 0 have to come before case Circle(double r)?
Show answer
Java tries cases from top to bottom. The unguarded case Circle(double r) matches every circle, so a guarded case placed below it could never run. The compiler rejects that order with a "dominated" error.