Sub topic 7
Deconstructing records inside switch patterns
This chapter assumes you know how to declare a sealed interface and its permitted records, and that you can read a basic switch expression. It also assumes you have seen the exhaustive switch from the previous chapter. The code needs Java 21 or later.
Until now, each case in a switch tested the type of a value and gave you a variable of that type. You then called accessor methods such as c.radius() to get at the data. A record pattern does both steps in one place. It tests the type, and it pulls the record's components into new variables.
What a record pattern is
A record pattern has the record's name followed by one nested pattern for each component, in declaration order.
record Point(int x, int y) {}
static String where(Object o) {
return switch (o) {
case Point(int x, int y) -> "point at " + x + "," + y;
default -> "something else";
};
}The case matches when o is a Point. Java then calls the accessors x() and y() and binds the results to the new variables x and y. Those variables are in scope only in that case's arrow expression or block, and in its when guard.
The nested patterns can be any of these:
| Nested pattern | Example | Matches |
|---|---|---|
| Type pattern | `int x`, `Expr e` | A component whose type is that type or a subtype of it |
| `var` pattern | `var x` | Any component value, with the type taken from the record declaration |
| Record pattern | `Num(var v)` | A component that is that record, with its own components deconstructed |
A var pattern always matches, including when the component is null. Use it when you only want the value and do not need to test its type.
A record pattern must name the right number of components, and each nested pattern must be compatible with the component's type. case Point(int x) and case Point(String x, int y) both fail to compile.
Deconstructing a sealed hierarchy
Record patterns work best with sealed interfaces, because the compiler can check that every variant is handled. The expression tree below is the standard example. permits is omitted because all three records are in the same compilation unit and directly implement Expr.
public class Main {
sealed interface Expr {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
static int eval(Expr e) {
return switch (e) {
case Num(var v) -> v;
case Add(var l, var r) -> eval(l) + eval(r);
case Mul(var l, var r) -> eval(l) * eval(r);
};
}
static String show(Expr e) {
return switch (e) {
case Num(var v) -> String.valueOf(v);
case Add(var l, var r) -> "(" + show(l) + " + " + show(r) + ")";
case Mul(var l, var r) -> "(" + show(l) + " * " + show(r) + ")";
};
}
public static void main(String[] args) {
Expr e = new Add(new Mul(new Num(1), new Num(7)), new Add(new Num(2), new Num(3)));
System.out.println(show(e));
System.out.println(eval(e));
}
}Save this as Main.java and run java Main.java. It prints ((1 * 7) + (2 + 3)) and then 12.
There is no default branch. Each pattern, Num(var v), Add(var l, var r) and Mul(var l, var r), matches every instance of its record, and together they cover every permitted subtype of Expr. If you later add a fourth record to Expr, both switches stop compiling until you handle it.
Nested patterns
A record pattern can contain other record patterns, so you can match the shape of a whole subtree. The next method rewrites an expression using three rules: fold two constants, drop a multiplication by zero, and drop a multiplication by one. Add it to the Main class above.
static Expr simplify(Expr e) {
return switch (e) {
case Add(Num(var a), Num(var b)) -> new Num(a + b);
case Mul(Num(var a), var r) when a == 0 -> new Num(0);
case Mul(Num(var a), var r) when a == 1 -> r;
case Add(var l, var r) -> new Add(simplify(l), simplify(r));
case Mul(var l, var r) -> new Mul(simplify(l), simplify(r));
case Num n -> n;
};
}Calling show(simplify(e)) on the expression from main prints (7 + 5). The method makes one pass. It does not fold the final Add(Num(7), Num(5)), because the result of a rewrite is not simplified again.
The first case Add(Num(var a), Num(var b)) matches only when both children are Num records. If either child is some other Expr, matching moves on to the next case. Without nested patterns you would write nested if statements with casts.
Guards and case order
A when guard adds a boolean condition to a case. The case matches only if the pattern matches and the guard is true. The bindings from the pattern are available in the guard, as a is in when a == 0.
Case order matters in two ways:
- The compiler rejects a case that an earlier case already covers, because that case could never run. If you put
case Add(var l, var r)beforecase Add(Num(var a), Num(var b)), the second one is a compile error. - A guarded case does not count as covering its type for exhaustiveness. In
simplify, the twoMul(Num(var a), var r) when ...cases are not enough on their own. The unguardedMul(var l, var r)is still needed.
Put the more specific and guarded cases first, and the general case for each record last.
Exhaustiveness through nested patterns
The compiler checks exhaustiveness across nested patterns, not only at the top level. The next program has a record whose components are sealed, and it has four cases, one for each combination.
public class Combine {
sealed interface Opt {}
record Some(int value) implements Opt {}
record None() implements Opt {}
record Both(Opt first, Opt second) {}
static int total(Both b) {
return switch (b) {
case Both(Some(var x), Some(var y)) -> x + y;
case Both(Some(var x), None n) -> x;
case Both(None n, Some(var y)) -> y;
case Both(None n, None m) -> 0;
};
}
public static void main(String[] args) {
System.out.println(total(new Both(new Some(3), new Some(4))));
System.out.println(total(new Both(new Some(2), new None())));
}
}The output is 7 and then 2. The compiler works out that two possibilities for first times two for second gives four combinations, and that the four cases cover them all. If you delete any one case, the switch no longer compiles and the error says it does not cover all possible input values. This is the main benefit of the feature. A missing combination becomes a compile error instead of a bug found at run time.
Note that None() is a record with no components. Its record pattern is written None(), and the type pattern None n also works when you do not need to look inside.
Generic records and type inference
You can omit the type arguments of a generic record in a pattern. The compiler infers them from the type of the value you are matching. This applies to the sealed Result type from earlier in the tutorial.
sealed interface Result<T> permits Ok, Err {}
record Ok<T>(T value) implements Result<T> {}
record Err<T>(String message) implements Result<T> {}
static String describe(Result<Integer> r) {
return switch (r) {
case Ok(var v) -> "value " + (v + 1);
case Err(var m) -> "error " + m;
};
}Here the selector has type Result<Integer>, so Ok(var v) is inferred as Ok<Integer> and v has type Integer. This is why v + 1 compiles. Writing Ok<Integer>(var v) is also allowed and means the same thing.
null and failures
Three behaviors catch people out:
- A
switchover anullselector throwsNullPointerException, unless one of the cases iscase null. A record pattern never matchesnull. - A component that is
nullis handled differently depending on the nested pattern. Avarpattern or a type pattern that covers the whole component type matches it. A nested record pattern does not. Withnew Add(null, new Num(1)), the caseAdd(Num(var a), Num(var b))does not match, butAdd(var l, var r)does, withlbound tonull. Insimplify, that call would then reachsimplify(null)and throw. - Matching calls the record's accessor methods. If an accessor throws an exception, the switch throws a
MatchExceptionwith that exception as its cause. This is rare with the default accessors, but it can happen if you override an accessor.
Also remember that sealed exhaustiveness is checked when you compile. If you recompile only the sealed interface after adding a new permitted record, and not the class holding the switch, the old switch has no case for it. At run time that switch throws a MatchException. Rebuilding everything, as normal build tools do, avoids this.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `incorrect number of nested patterns` | Fewer or more patterns than record components | Match the declaration exactly, using `var` for components you ignore |
| `this case label is dominated by a preceding case label` | A general case appears before a specific one | Move the specific or guarded case up |
| `the switch expression does not cover all possible input values` | A variant or a nested combination is missing, or a case relies on a guard | Add the case, or add an unguarded case for that record |
| `NullPointerException` at the switch | The selector was `null` | Add `case null`, or check for `null` before the switch |
| Pattern with a primitive component does not compile as expected | Using a boxed type such as `Integer x` against an `int` component | Use `int x` or `var x` |
Summary of what to remember
- A record pattern tests the type and extracts the components in one step.
- Nested patterns let one case describe a whole shape, and the compiler checks exhaustiveness through them.
- Guarded cases never make a switch exhaustive, so keep an unguarded fallback for each record.
varmatches anything, includingnull. A nested record pattern never matchesnull.
Exercise
Using the Expr hierarchy from this chapter (Num, Add, Mul), write a switch expression method static Expr negate(Expr e) that returns new Num(-v) for Num(var v), and otherwise multiplies the whole expression by new Num(-1). Then explain why adding a guard when v == 0 to case Num(var v) would make the switch fail to compile unless you add another case.
Show answer
One solution is return switch (e) { case Num(var v) -> new Num(-v); case Add(var l, var r) -> new Mul(new Num(-1), e); case Mul(var l, var r) -> new Mul(new Num(-1), e); };. A guarded case does not count towards exhaustiveness, because the compiler cannot prove the guard is true for every Num. With case Num(var v) when v == 0, a Num whose value is not zero would match no case, so the compiler rejects the switch. You fix it by adding an unguarded case Num(var v) after the guarded one, or by keeping a single unguarded case.
Exercise
Given record Pair(Opt a, Opt b) where Opt is sealed and permits only the records Some(int v) and None(), how many cases does a switch over Pair need if every case uses nested record patterns with no var in the top positions, and why?
Show answer
Four. Each of the two components can be Some or None, so there are 2 x 2 = 4 combinations: Some/Some, Some/None, None/Some and None/None. Leaving out any combination makes the switch non-exhaustive. You could use fewer cases by using a total pattern such as Pair(var a, None n), which covers both values of a in one case.