Sub topic 13
Next step: record patterns
This chapter assumes you can write a type pattern with instanceof, you know how binding variables are scoped with &&, ! and early returns, and you know what a Java record is (a class with a fixed list of components, an automatic constructor and an accessor method per component). Record patterns need Java 21 or later. They were previews in Java 19 and 20, and Java 21 finalized them (JEP 440).
From type pattern to record pattern
A type pattern tests a type and gives you one variable. If the value is a record, you usually then call its accessors to get the parts:
record Point(int x, int y) {}
static String describeOld(Object o) {
if (o instanceof Point p) {
int x = p.x();
int y = p.y();
return "x=" + x + ", y=" + y;
}
return "not a point";
}A record pattern does the type test and the component extraction in one step. Its syntax is the record's name followed by a parenthesized list of subpatterns, one per component, in declaration order:
public class RecordPatternDemo {
record Point(int x, int y) {}
static String describe(Object o) {
if (o instanceof Point(int x, int y)) {
return "x=" + x + ", y=" + y;
}
return "not a point";
}
public static void main(String[] args) {
System.out.println(describe(new Point(3, 4)));
System.out.println(describe("text"));
}
}The program prints x=3, y=4 and then not a point.
When the value is a Point, the runtime calls the accessors x() and y(). It then matches each result against the matching subpattern. Here int x and int y are type patterns, so they declare binding variables of type int. There is no p variable. If you also need the whole record, use a type pattern in a separate test, or read the components from the record pattern only.
How a match proceeds
The match is a sequence of checks that stops at the first failure.
Two consequences follow. A null value never matches a record pattern, for the same reason null instanceof Point is false. Also, the bindings exist only when the whole pattern matches, so they follow the same flow-scoping rules you already know.
Nested patterns
Subpatterns can themselves be record patterns. This is where record patterns save the most code:
public class NestedDemo {
record Point(int x, int y) {}
record Line(Point from, Point to) {}
static boolean isVertical(Object o) {
return o instanceof Line(Point(var x1, var y1), Point(var x2, var y2))
&& x1 == x2 && y1 != y2;
}
public static void main(String[] args) {
System.out.println(isVertical(new Line(new Point(1, 0), new Point(1, 5))));
System.out.println(isVertical(new Line(new Point(1, 0), new Point(2, 5))));
}
}This prints true and then false. Without the pattern you would test the type, then call from() and to(), then call x() and y() on each result. The bindings x1, y1, x2 and y2 are in scope on the right side of &&, as with a type pattern.
Using var
Inside a record pattern, var x is a type pattern whose type is the component's declared type. In Point(var x1, var y1) both bindings are int. It's shorthand, and it keeps nested patterns readable. You can only use var as a subpattern inside a record pattern. o instanceof var x is not allowed.
Scope rules still apply
Everything from the scoping chapters carries over. The bindings are in scope where the compiler can prove the match succeeded.
static int sumOrZero(Object o) {
if (!(o instanceof Point(int x, int y))) {
return 0;
}
return x + y; // x and y are in scope: the if body cannot complete normally
}The || mistake also carries over. This does not compile, because the right side of || runs when the match failed:
// Does not compile: x is not in scope when the match fails.
// return o instanceof Point(int x, int y) || x > 0;You also cannot reuse a name. Two bindings in the same pattern cannot share a name, and a binding cannot shadow a local variable that is already in scope. Point(int x, int x) is an error.
Matching on a component's type
A subpattern can be narrower than the component's declared type. Then it acts as an extra test on that component:
public class BoxDemo {
record Box<T>(T value) {}
static String inspect(Box<Object> box) {
if (box instanceof Box<Object>(String s)) {
return "string of length " + s.length();
}
if (box instanceof Box<Object>(Integer i)) {
return "integer " + (i + 1);
}
return "something else";
}
public static void main(String[] args) {
System.out.println(inspect(new Box<>("hello")));
System.out.println(inspect(new Box<>(41)));
System.out.println(inspect(new Box<>(2.5)));
}
}The output is string of length 5, integer 42 and something else. The component's declared type is Object, so String s is a real test, not a formality. This is the same cast-or-fail check as a top-level type pattern, applied to the component.
Null components
The record itself can never be null when it matches, but a component can be. What happens depends on whether the subpattern is total for the component type. A pattern is total (also called unconditional) when every value of the component type matches it, so no runtime test is needed.
- A total subpattern matches
null.String sagainst aStringcomponent is total, andvar salways is. - A non-total subpattern does not match
null.String sagainst anObjectcomponent is a real type test, andnullfails it.
public class NullComponentDemo {
record Box<T>(T value) {}
public static void main(String[] args) {
Box<String> a = new Box<>(null);
if (a instanceof Box<String>(String s)) {
System.out.println("matched, s=" + s);
}
Box<Object> b = new Box<>(null);
if (b instanceof Box<Object>(String s)) {
System.out.println("matched, s=" + s);
} else {
System.out.println("no match");
}
}
}This prints matched, s=null and then no match. This is a common source of surprise when you expect every binding to be non-null. If a component may be null and your pattern is total, check the binding yourself.
Primitive components must match exactly
In Java 21, a subpattern for a primitive component must be that same primitive type. Neither widening nor boxing is applied.
record Pair(int a, int b) {}
static boolean test(Object o) {
// Does not compile in Java 21: long is not int.
// return o instanceof Pair(long a, int b);
return o instanceof Pair(int a, int b) && a < b;
}Use var when you don't want to repeat component types. It always picks the right one. Later Java versions have previewed primitive patterns that relax this rule, but do not rely on them in code that targets Java 21.
Generic records and inference
You may omit the type arguments of a generic record in a pattern. The compiler infers them from the type of the value being tested:
static int length(Box<String> box) {
if (box instanceof Box(var s)) { // infers Box<String>, s is String
return s.length();
}
return -1;
}Inference follows the same rule as for type patterns. The cast from the value's type to the record type must be checked, or the compiler rejects it as an unchecked conversion. Spelling the type arguments out, as in Box<String>(var s), is often clearer and has the same effect.
When an accessor throws
The runtime calls your record's accessor methods. For ordinary records these are plain field reads that cannot fail. If you override an accessor and it throws, the pattern does not let that exception escape directly. The runtime wraps it in a java.lang.MatchException, with the original exception as the cause.
record Risky(int v) {
public int v() {
throw new IllegalStateException("boom");
}
}
// new Risky(1) instanceof Risky(int v) -> throws MatchException, cause: IllegalStateExceptionCommon errors
| Mistake | What happens | Fix | Column | Column |
|---|---|---|---|---|
| Wrong number of subpatterns | Compile error | Give one subpattern per component | ||
| `Point(long x, int y)` for `int` components | Compile error in Java 21 | Use `int`, or `var` | ||
| Using a binding after `\ | \ | ` | Compile error | Use `&&`, or restructure the condition |
| Expecting `null` to match a non-total subpattern | The match fails | Use a total pattern, or test for null explicitly | ||
| Testing a record pattern against a type unrelated to the record | Compile error | Check that the value's type could be the record | ||
| Reusing a binding name | Compile error | Rename one of the bindings |
Where this leads
Record patterns are one half of a pair. Type patterns and record patterns also work as case labels in switch. The next and last chapter shows how the early-return guard idiom and record patterns combine there, so a chain of if (o instanceof ...) tests becomes a single switch.
Exercise
Given record Pair(Object first, Object second) {}, what does new Pair("a", null) instanceof Pair(String s, String t) evaluate to, and why?
Show answer
It evaluates to false. The first subpattern matches, since "a" is a String. The second component is declared as Object, so String t is not a total pattern for it. It is a real type test, and null fails a type test. The whole match fails, so neither s nor t is assigned.
Exercise
Rewrite this method using a record pattern, keeping the same behavior for null and non-Rect inputs. Which Java version does it need at minimum? record Rect(int w, int h) {} static int area(Object o) { if (o instanceof Rect) { Rect r = (Rect) o; return r.w() * r.h(); } return 0; }
Show answer
static int area(Object o) { if (o instanceof Rect(int w, int h)) { return w * h; } return 0; } Null returns 0 because a record pattern never matches null. The code needs Java 21, where record patterns became final.