Sub topic 9
Deconstructing records with record patterns
A record pattern tests whether a value is an instance of a record type. If it is, the pattern also pulls out the record's components in the same step. This chapter covers the syntax, the matching rules, how null is treated, and how record patterns combine with guards and sealed types.
Prerequisites
This chapter assumes you know:
- Type patterns in
instanceofand inswitch, includingwhenguards. - Records: a
record Point(int x, int y) {}declaration, its canonical constructor, and its accessor methodsx()andy(). - Sealed interfaces and exhaustive switches.
- JDK 21 or newer. Record patterns are final in Java 21.
The problem record patterns solve
With a type pattern alone, you still extract components by hand:
if (o instanceof Point p) {
int x = p.x();
int y = p.y();
// use x and y
}A record pattern does the test and the extraction together:
if (o instanceof Point(int x, int y)) {
// x and y are already bound here
}The pattern Point(int x, int y) has two parts. Point is the record type to test for. The list in parentheses has one component pattern for each record component, in declaration order. The variables x and y are binding variables, and their scope follows the usual flow rules for pattern variables.
A complete example
public class RecordPatternDemo {
record Point(int x, int y) {}
static String describe(Object o) {
if (o instanceof Point(int x, int y)) {
return "point at " + x + ", " + y;
}
return "not a point";
}
public static void main(String[] args) {
System.out.println(describe(new Point(3, 4)));
System.out.println(describe("hello"));
System.out.println(describe(null));
}
}Run it with java RecordPatternDemo.java. The output is:
point at 3, 4
not a point
not a pointThe null call prints "not a point" because a record pattern never matches null, just as instanceof is false for null.
How a record pattern matches
Matching happens in a fixed order.
- The value must not be
null. - The value must be an instance of the record type.
- The compiler-generated code calls each accessor method, in component order.
- Each result is matched against its component pattern.
- The whole pattern matches only if every component pattern matches.
Two consequences follow from step 3. The pattern calls the accessor methods, not the fields. If a record overrides an accessor, the pattern sees the overridden value. The binding names are also yours to choose. The pattern Point(int a, int b) is valid, because components are matched by position, not by name.
Component patterns
Each component position accepts a pattern. Here are the forms that work at this level.
| Component pattern | Example | Matches |
|---|---|---|
| Type pattern with the component's own type | `int x` | Always, including a `null` reference component |
| `var` pattern | `var x` | Always; the compiler infers the component type |
| Type pattern with a narrower type | `String s` for an `Object` component | Only when the component is a non-null `String` |
| Nested record pattern | `Point(var a, var b)` | Only when the component is a non-null `Point` whose own components match |
The first two rows are called total (unconditional) for the component type. A total pattern matches every value, including null. A narrower type pattern is a real test, and null fails it.
Null components
This distinction matters in practice. Consider a record with Object components:
public class NullComponents {
record Pair(Object first, Object second) {}
static String test(Pair p) {
return switch (p) {
case Pair(String s, var other) -> "string first: " + s;
case Pair(Object o, var other) -> "first is " + o;
};
}
public static void main(String[] args) {
System.out.println(test(new Pair("hi", 1)));
System.out.println(test(new Pair(42, 1)));
System.out.println(test(new Pair(null, 1)));
}
}The output is:
string first: hi
first is 42
first is nullFor new Pair(null, 1), the first case fails because String s is not total for Object, so it rejects null. The second case uses Object o, which is total, so it accepts the null. The switch is exhaustive because the second case covers every non-null Pair.
The record value itself is different. If p is null, the switch throws NullPointerException, unless you add a case null label. That label was covered in an earlier chapter.
Using record patterns in switch with guards
Record patterns are patterns, so all the switch rules from earlier chapters apply: guards, dominance, and exhaustiveness.
public class Classify {
record Point(int x, int y) {}
static String classify(Object o) {
return switch (o) {
case Point(int x, int y) when x == 0 && y == 0 -> "origin";
case Point(int x, int y) when x == y -> "diagonal point " + x;
case Point(var x, var y) -> "point " + x + "," + y;
default -> "other";
};
}
public static void main(String[] args) {
System.out.println(classify(new Point(0, 0)));
System.out.println(classify(new Point(5, 5)));
System.out.println(classify(new Point(1, 2)));
System.out.println(classify("text"));
}
}The output is origin, diagonal point 5, point 1,2, and other. The guarded cases come before the unguarded Point(var x, var y). Reversing the order would make the guarded cases unreachable, and the compiler would report a dominance error.
You can also combine a record pattern with && in an if:
if (o instanceof Point(int x, int y) && x == y) {
System.out.println("on the diagonal");
}Record patterns on a sealed hierarchy
Record patterns combine well with sealed interfaces. When every permitted subtype is a record, the switch can take apart each case and still be checked for exhaustiveness.
public class Areas {
sealed interface Shape permits Circle, Rect {}
record Circle(double radius) implements Shape {}
record Rect(double width, double height) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) -> w * h;
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(1.0)));
System.out.println(area(new Rect(2.0, 3.0)));
}
}There is no default branch. The compiler sees that Circle(double r) covers every Circle and Rect(double w, double h) covers every Rect. If you add a third permitted record later, this switch stops compiling until you handle it. That is the benefit of omitting default.
A record pattern with guards, or with narrower component patterns, does not cover its record type on its own. For example, case Rect(double w, double h) when w > 0 leaves some Rect values unmatched. The compiler then asks for another Rect case or a default.
Common errors
- Wrong number of components.
Point(int x)does not compile for a two-component record. Every component needs a pattern. - Incompatible component type.
Point(String s, int y)is rejected, because anintcomponent can never be aString. - Expecting a match on
null.Point(var x, var y)does not match anullPoint. Only the components can benull, and only against total patterns. - Reusing a name. Two binding variables in one pattern cannot share a name, and a binding cannot reuse the name of a local variable already in scope.
- Assuming names matter. Matching is by position. If you swap
xandyin the pattern list, you get swapped values with no warning.
Exercise
Given record Pair(Object first, Object second) {}, which of these cases matches new Pair(null, "x"): (a) case Pair(String s, var t), (b) case Pair(Object o, var t), (c) case Pair(var o, String t)? Explain.
Show answer
(b) and (c) both have a pattern for the first component that matches null, and only (b) and (c) can match. In (b), Object o is total for an Object component, so it accepts null, and var t is total too. In (c), var o is total, and String t matches the non-null string "x". Case (a) fails because String s is a narrower type pattern and does not match null. If the cases appear in the order (a), (b), (c), the switch selects (b), the first one that matches. Placing (c) before (b) makes (c) the selected case.
Exercise
Write a switch expression static String kind(Object o) using record Point(int x, int y) that returns "origin" for a point at (0, 0), "x-axis" for any other point with y equal to 0, "y-axis" for any other point with x equal to 0, "point" for any other Point, and "other" for non-points. Why must the origin case come first?
Show answer
static String kind(Object o) {
return switch (o) {
case Point(int x, int y) when x == 0 && y == 0 -> "origin";
case Point(int x, int y) when y == 0 -> "x-axis";
case Point(int x, int y) when x == 0 -> "y-axis";
case Point(var x, var y) -> "point";
default -> "other";
};
}
The origin case must come first because the later guards are less specific. A point at (0, 0) satisfies both y == 0 and x == 0, so if either of those cases came first, the origin would be reported as an axis point. The unguarded Point(var x, var y) must come after all guarded Point cases, or the compiler reports them as dominated.