Sub topic 10
Nesting record patterns
This chapter assumes you know how a basic record pattern works (case Point(int x, int y)). It also assumes you are comfortable with sealed interfaces, when guards, and dominance, and that you have JDK 21 or newer. Everything here is final in Java 21, except unnamed patterns, which this chapter doesn't use.
Patterns inside patterns
A record pattern lists one sub-pattern for each component of the record. Each sub-pattern can be a type pattern, var, or another record pattern. That last option is what nesting means.
Take two records, where one contains the other:
record Point(int x, int y) {}
record Line(Point start, Point end) {}
public class NestedDemo {
static boolean isHorizontal(Object o) {
return switch (o) {
case Line(Point(var x1, var y1), Point(var x2, var y2)) -> y1 == y2;
default -> false;
};
}
public static void main(String[] args) {
System.out.println(isHorizontal(new Line(new Point(0, 5), new Point(9, 5))));
System.out.println(isHorizontal(new Line(new Point(0, 5), new Point(9, 6))));
System.out.println(isHorizontal(new Line(null, new Point(9, 5))));
System.out.println(isHorizontal("text"));
}
}This prints true, false, false, false.
Without nesting you would match Line l, call l.start() and l.end(), test each for Point, and call x() and y() on each. The nested pattern does all of that in one label and gives you four int variables.
The third call returns false because start is null. A record pattern never matches null, so Point(var x1, var y1) fails and the whole Line case fails. The value falls through to default.
How matching proceeds
A nested pattern is matched in a fixed order:
- The outer value is tested against the outer record type.
- The first component accessor is called, and its result is matched against the first sub-pattern.
- If that succeeds, the next component is handled the same way, left to right.
- The case matches only if every sub-pattern matches. The first failure stops the process and the next case is tried.
Two consequences follow from this order.
- Matching calls the record's accessor methods, not its fields directly. If a record overrides an accessor, the override runs. The compiler may also call an accessor more than once across several cases, so keep accessors free of side effects.
- A binding is only available in the body (and guard) of the case where it was declared. All names inside one pattern must be distinct.
Line(Point(var x, var y), Point(var x, var y))is a compile error becausexis declared twice.
Total sub-patterns and null
Whether a nested pattern matches null depends on the kind of sub-pattern:
| Sub-pattern | Component is `null` |
|---|---|
| `var v` | Matches, `v` is `null` |
| Type pattern whose type is the component's declared type (for example `Point p` for a `Point` component) | Matches, `p` is `null` |
| Type pattern with a narrower type (for example `String s` for an `Object` component) | Does not match |
| Record pattern | Does not match |
A pattern that matches every value of the component's type is called total (or unconditional). Total patterns are the only ones that accept null in a nested position. This program shows the difference:
record Pair(Object first, Object second) {}
public class NullDemo {
static String test(Pair p) {
return switch (p) {
case Pair(String s, Integer i) -> "string and int: " + s + ", " + i;
case Pair(Pair(var a, var b), var c) -> "nested pair, second is " + c;
case Pair(var a, var b) -> "anything: " + a + ", " + b;
};
}
public static void main(String[] args) {
System.out.println(test(new Pair("a", 1)));
System.out.println(test(new Pair(new Pair(1, 2), 3)));
System.out.println(test(new Pair(null, 1)));
System.out.println(test(new Pair(null, null)));
}
}The output is:
string and int: a, 1
nested pair, second is 3
anything: null, 1
anything: null, nullPair(null, 1) skips the first two cases because String s and Pair(...) both refuse null. The last case uses var, which is total, so it accepts it. The switch needs no default because Pair(var a, var b) already covers every non-null Pair.
Combining nesting with guards
Nested patterns test the shape of the data. A when guard tests values. Together they express rewrite rules compactly. This is a complete program:
sealed interface Expr permits Const, Add, Mul, Neg {}
record Const(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr operand) implements Expr {}
public class Simplifier {
static Expr simplify(Expr e) {
return switch (e) {
case Add(Const(var a), Const(var b)) -> new Const(a + b);
case Mul(Const(var a), var r) when a == 0 -> new Const(0);
case Mul(Const(var a), var r) when a == 1 -> r;
default -> e;
};
}
public static void main(String[] args) {
System.out.println(simplify(new Add(new Const(2), new Const(3))));
System.out.println(simplify(new Mul(new Const(0), new Neg(new Const(4)))));
System.out.println(simplify(new Mul(new Const(1), new Neg(new Const(4)))));
System.out.println(simplify(new Mul(new Const(2), new Const(4))));
}
}It prints:
Const[value=5]
Const[value=0]
Neg[operand=Const[value=4]]
Mul[left=Const[value=2], right=Const[value=4]]The two Mul cases have the same pattern and differ only in the guard. Guarded cases never count as covering a type for exhaustiveness, so the default is required. Remove it and the compiler reports that the switch does not cover all possible input values.
This version of simplify rewrites only the top node. A real simplifier would also call itself on the children.
Dominance between nested patterns
Dominance applies to record patterns as well. A record pattern dominates another when both name the same record type and each sub-pattern of the first dominates the matching sub-pattern of the second. A total pattern such as var r dominates any record pattern for the same component type.
static Expr bad(Expr e) {
return switch (e) {
case Add(Const(var a), var r) -> r;
case Add(Const(var a), Const(var b)) -> new Const(a + b); // compile error: dominated
default -> e;
};
}The first case already matches every Add whose left side is a Const, so the second can never run. Swap the two cases to fix it: put the more specific case first.
A guarded case does not dominate later cases, because the guard may fail. An unguarded case does.
Exhaustiveness through nested sealed types
The compiler checks exhaustiveness through nesting. If a component's type is sealed, the nested patterns must cover all its permitted subtypes.
static String describeAdd(Add add) {
return switch (add) {
case Add(Const l, Expr r) -> "constant on the left";
case Add(Add l, Expr r) -> "sum on the left";
case Add(Mul l, Expr r) -> "product on the left";
case Add(Neg l, Expr r) -> "negation on the left";
};
}The left component has type Expr, which permits exactly four subtypes. All four appear, and the right component uses the total pattern Expr r, so no default is needed. Delete any one case and the switch stops compiling. If you later add a fifth permitted subtype of Expr, this method stops compiling too, which is the behavior you want.
Common mistakes
- Expecting
nullto match a nested record pattern. It never does. Use a total pattern for that component, or handle the outer value in a separate case. - Putting a broad case before a narrow one. The compiler reports dominance, but only when it can see it. Guards can hide ordering mistakes that the compiler accepts but that give wrong results.
- Nesting too deep. A pattern three levels down is hard to read. If a case spans more than one line, bind the middle value with a type pattern and match it in a helper method.
- Reusing a binding name. Names must be unique within one pattern. The same name may be reused across different cases.
- Adding
defaultto silence the compiler. On a sealed hierarchy, adefaulthides the error you want when a new subtype is added.
Exercise
Given record Box(Object content) {}, which of these inputs does case Box(String s) match: new Box("hi"), new Box(null), new Box(42)? Which case would you add last so that every non-null Box is handled?
Show answer
Only new Box("hi") matches. String s is not total for an Object component, so it rejects null and 42. Add case Box(var c) (or case Box(Object c)) last. Both are total, so they match every non-null Box, including one whose content is null.
Exercise
Using the Expr records from this chapter, write a case for simplify that rewrites Neg(Neg(x)) to x. Then explain whether it can be placed before or after the Add(Const(var a), Const(var b)) case.
Show answer
case Neg(Neg(var x)) -> x; does the rewrite. The order does not matter. The two patterns have different outer record types (Neg and Add), so neither dominates the other. Only the default must stay last.