Sub topic 3
Nesting Record Patterns in Java
Assume you know interfaces, inheritance, switch expressions, instanceof, and basic generics. Record patterns require JDK 21 or newer. Unnamed patterns require JDK 22 or newer.
Nesting record patterns
A record pattern can contain another record pattern. This lets one case inspect several levels of data without calling accessors manually.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static boolean isHorizontal(Object value) {
return switch (value) {
case Line(Point(var x1, var y1), Point(var x2, var y2))
-> y1 == y2;
default -> false;
};
}The outer pattern matches Line. Its two nested patterns match the Point components. The var patterns bind their coordinates.
Generic records and type inference in patterns
Record patterns can use parameterized records. The component pattern supplies the useful type information:
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Box<T>(T content) {}
static String describe(Box<Shape> box) {
return switch (box) {
case Box<Shape>(Circle c) -> "circle";
case Box<Shape>(Shape s) -> "another shape";
};
}The compiler knows that the content is a Shape, so the nested pattern can test for Circle without a cast.
Ignoring components with unnamed patterns
Java 22 adds _ for a value that must match but is not needed:
static String describeCircle(Box<Shape> box) {
return switch (box) {
case Box<Shape>(Circle _) -> "circle";
case Box<Shape>(Shape _) -> "other shape";
};
}An unnamed pattern documents that the component is intentionally ignored.
> callout note > Keep a named pattern when you need the value. Use _ when only the component's type matters.
When a switch throws MatchException
An exhaustive switch normally matches every permitted value. MatchException can still occur if separate compilation leaves the runtime hierarchy or enum constants different from what the compiler saw. A record pattern can also fail when a nested value does not match and no later case handles it. Handle null explicitly when it is a valid input.
Putting it together: an expression evaluator
Sealed records make a small evaluator data-oriented: the data types describe the cases, and the switch describes the operation.
sealed interface Expr permits Const, Add, Mul {}
record Const(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
static int eval(Expr expression) {
return switch (expression) {
case Const(var value) -> value;
case Add(var left, var right) -> eval(left) + eval(right);
case Mul(var left, var right) -> eval(left) * eval(right);
};
}Exercise
What does eval(new Add(new Const(2), new Const(3))) return?
Show answer
It returns 5.