Introduction
Java 16, released in March 2021, finalised records (JEP 395) and added pattern matching for instanceof (JEP 394). Together these two features lay the groundwork for the java 16 record patterns feature, which was proposed in Java 17 as JEP 405 (preview) and finalised in Java 21 as JEP 440. A record pattern is a pattern that destructures a record instance by binding its components to fresh local variables in a single expression. Where instanceof Point p binds p to the entire record value, the record pattern instanceof Point(int x, int y) binds x and y directly to the components, eliminating the subsequent p.x() and p.y() accessor calls.
For a Java learner, java 16 record patterns is the gateway to writing concise destructuring code over algebraic data types modelled as records. Record patterns pair naturally with sealed classes (finalised in Java 17) and pattern matching for switch (finalised in Java 21) to give Java a fully modern pattern-matching system. This post walks through the record pattern syntax, nested record patterns, the combination with switch, and the rules for type inference in patterns.
What is Java 16 Record Patterns?
A record pattern is a pattern of the form RecordType(componentPattern1, componentPattern2, ...). It matches a value if and only if the value is an instance of RecordType and the inner component patterns match the corresponding component values. For example, instanceof Point(int x, int y) matches a Point instance, binds x to the int returned by the component accessor of the same name, and binds y to the other int component. The component patterns can be type patterns (binding the component to a fresh variable), or they can themselves be record patterns (for nested destructuring), or they can be the unconditionally matching underscore pattern (Java 22+) to ignore a component.
Conceptually, record patterns belong to the family of structural destructuring constructs, similar to JavaScript's object destructuring, Scala's case-class unapply, and Python's tuple unpacking. The Java version is conservative: it only matches values whose runtime class is the exact record type, not subclasses (records are final so subclasses cannot exist). The compiler can verify the number and types of component patterns against the record header at compile time, which catches a class of typos early.
How Java 16 Record Patterns Works - Step by Step
Step 1: Declare a record type. The record header defines the components and their types, in order. For example, record Point(int x, int y) declares a record with two int components named x and y, in that order.
Step 2: Write the pattern. The pattern Point(int a, int b) destructures a Point value, binding its first component (x) to a fresh variable a and its second component (y) to a fresh variable b. The order of the pattern components matches the order of the record header components, not the names of the binding variables.
Step 3: Use the pattern in an instanceof check. The expression obj instanceof Point(int a, int b) checks the runtime type of obj, casts it to Point if it is a Point, and binds the component values to a and b in the truthy branch. The names a and b are local to the truthy branch, just like the variable bound by a regular instanceof pattern.
Step 4: Use the pattern in a switch expression (Java 21). The switch arm case Point(int a, int b) -> ... destructures the matched Point in the arm body. The arm fires only when the selector value is a Point, and the variables a and b are in scope inside the arm body.
Step 5: Nest record patterns for deep destructuring. If you have a record Line(Point start, Point end), the pattern Line(Point(int x1, int y1), Point(int x2, int y2)) destructures the Line and both inner Points in one expression, binding four int variables x1, y1, x2, y2.
Java Program for Record Patterns
import java.util.List;
public class RecordPatternsDemo {
// (1) Simple record with two components
public record Point(int x, int y) {}
// (2) Nested record: a Line is made of two Points
public record Line(Point start, Point end) {}
// (3) A record with mixed component types
public record Segment(Point from, double length) {}
// (4) Sealed hierarchy of shapes as records
public sealed interface Shape permits Dot, Disc, Rect {}
public record Dot(Point p) implements Shape {}
public record Disc(Point center, int radius) implements Shape {}
public record Rect(Point corner, int w, int h) implements Shape {}
// (5) Method that uses simple record pattern in instanceof
static String describePoint(Object o) {
if (o instanceof Point(int x, int y)) {
return "Point(" + x + ", " + y + ")";
}
return "not a Point";
}
// (6) Method that uses nested record patterns
static String describeLine(Object o) {
if (o instanceof Line(Point(int x1, int y1),
Point(int x2, int y2))) {
return "Line from (" + x1 + ", " + y1 + ") to ("
+ x2 + ", " + y2 + ")";
}
return "not a Line";
}
// (7) Mixed-pattern record destructure
static String describeSegment(Object o) {
if (o instanceof Segment(Point(int x, int y), double len)) {
return "Segment at (" + x + ", " + y + ") length " + len;
}
return "not a Segment";
}
// (8) Switch expression with record patterns over a sealed hierarchy
static String describeShape(Shape s) {
return switch (s) {
case Dot(Point(int x, int y)) ->
"Dot at (" + x + ", " + y + ")";
case Disc(Point(int cx, int cy), int r) ->
"Disc centred at (" + cx + ", " + cy + ") r=" + r;
case Rect(Point(int rx, int ry), int w, int h) ->
"Rect at (" + rx + ", " + ry + ") " + w + "x" + h;
};
}
// (9) Combining record patterns with if-condition refinement
static boolean isHorizontal(Object o) {
return o instanceof Line(Point(int x1, int y1),
Point(int x2, int y2))
&& y1 == y2;
}
// (10) Quadrant classifier using only the destructured components
static String classify(Point p) {
if (p instanceof Point(int x, int y)) {
if (x > 0 && y > 0) return "Q1";
if (x < 0 && y > 0) return "Q2";
if (x < 0 && y < 0) return "Q3";
if (x > 0 && y < 0) return "Q4";
return "axis";
}
return "not a point";
}
public static void main(String[] args) {
// (5)
System.out.println("(5) " + describePoint(new Point(3, 4)));
System.out.println("(5) " + describePoint("hello"));
// (6)
System.out.println("(6) " + describeLine(
new Line(new Point(0, 0), new Point(5, 5))));
System.out.println("(6) " + describeLine(42));
// (7)
System.out.println("(7) " + describeSegment(
new Segment(new Point(2, 3), 7.5)));
// (8)
List<Shape> shapes = List.of(
new Dot(new Point(1, 1)),
new Disc(new Point(0, 0), 5),
new Rect(new Point(2, 2), 10, 20));
for (Shape s : shapes) {
System.out.println("(8) " + describeShape(s));
}
// (9)
System.out.println("(9) horizontal: "
+ isHorizontal(new Line(new Point(1, 2), new Point(5, 2))));
System.out.println("(9) horizontal: "
+ isHorizontal(new Line(new Point(1, 2), new Point(5, 3))));
// (10)
System.out.println("(10) (3,4): " + classify(new Point(3, 4)));
System.out.println("(10) (-3,4): " + classify(new Point(-3, 4)));
System.out.println("(10) (-3,-4): " + classify(new Point(-3, -4)));
System.out.println("(10) (3,-4): " + classify(new Point(3, -4)));
System.out.println("(10) (0,0): " + classify(new Point(0, 0)));
}
}
Code Explanation - Line by Line
Record (1) Point is a simple two-component record. Records (2) and (3) build on Point: Line nests two Points, and Segment nests one Point plus a double length component. The sealed interface (4) Shape and its three record subclasses Dot, Disc, and Rect model a small algebraic data type that the switch expression in describeShape will exhaustively dispatch over.
Method (5) describePoint uses the simplest record pattern instanceof Point(int x, int y) to destructure the Point value into its components x and y in one shot. The output string is built using the destructured variables directly, with no accessor calls.
Method (6) describeLine uses a nested record pattern instanceof Line(Point(int x1, int y1), Point(int x2, int y2)). The outer pattern matches a Line, and each inner pattern matches the corresponding Point component. The result is four local variables x1, y1, x2, y2 bound in one expression. Without record patterns, the same code would need two intermediate variables (Line line = (Line) o; Point start = line.start(); Point end = line.end(); int x1 = start.x(); ...).
Method (7) describeSegment shows a record pattern that combines a nested Point pattern with a simple double component: instanceof Segment(Point(int x, int y), double len). The pattern binds x and y from the inner Point and len from the outer Segment component.
Method (8) describeShape is the canonical Java 21 pattern-matching switch expression with record patterns. Each arm is a case label with a record pattern that destructures the matched shape. Because Shape is sealed with three record subclasses, the compiler verifies exhaustiveness without a default arm. If you added a fourth shape kind to the permits list without updating describeShape, the compiler would emit an error.
Method (9) isHorizontal uses a record pattern in an instanceof check combined with a refinement condition && y1 == y2. The variables y1 and y2 are bound by the pattern, and the refinement compares them. The && short-circuits: if the value is not a Line, the pattern fails and the refinement is not evaluated.
Method (10) classify uses a record pattern to destructure a Point into x and y, then uses a sequence of if statements to classify the point into one of the four quadrants. The variables x and y are in scope for the entire body of the truthy branch, so the if-else chain can refer to them without an extra cast.
Sample Input and Output
Input: args = [] (uses fixed demo data) Output: (5) Point(3, 4) (5) not a Point (6) Line from (0, 0) to (5, 5) (6) not a Line (7) Segment at (2, 3) length 7.5 (8) Dot at (1, 1) (8) Disc centred at (0, 0) r=5 (8) Rect at (2, 2) 10x20 (9) horizontal: true (9) horizontal: false (10) (3,4): Q1 (10) (-3,4): Q2 (10) (-3,-4): Q3 (10) (3,-4): Q4 (10) (0,0): axis
The output confirms that the record pattern destructures the matched value in one shot, that nested patterns bind four variables from a single Line, that the sealed-hierarchy switch dispatches over Dot, Disc, and Rect exhaustively without a default arm, and that combining patterns with refinement conditions produces correct boolean results. The quadrant classifier returns "axis" for the origin (0,0), since none of the strict quadrant conditions matches when x and y are zero.
Common Mistakes to Avoid
The first mistake is supplying the wrong number of component patterns. The pattern Point(int x) for a record Point(int x, int y) is rejected by the compiler because the pattern has one component but the record header has two. Always supply exactly as many component patterns as the record declares.
The second mistake is supplying the wrong type for a component pattern. The pattern Point(String a, int b) for a record Point(int x, int y) is rejected because the first component is int, not String. The type in the component pattern must match the component type in the record header.
The third mistake is assuming record patterns match subclasses. Records are implicitly final, so the issue rarely arises, but a record pattern only matches when the runtime class of the value is exactly the named record type. A pattern Point(int x, int y) does not match a value whose class is a subinterface of Point (which is impossible because Point is final) and does not match null.
The fourth mistake is forgetting that nested record patterns bind fresh variables in the same scope. The pattern Line(Point(int x1, int y1), Point(int x2, int y2)) binds four distinct variables; reusing a name like x in both inner patterns would be rejected as a duplicate variable declaration.
Real-World Applications
In production Java code, record patterns are heavily used in domain modelling and event processing. Spring Framework's ApplicationEvent dispatcher uses record patterns to destructure event payloads (which are typically records like OrderCreated, OrderShipped) in modern Spring Boot 3.x applications. The Jackson JSON library can bind JSON to records and uses record patterns internally when post-processing tokens.
In build tooling, the Gradle build tool's task-action dispatcher uses record patterns to destructure task configuration events. The Maven build tool's plugin executor uses record patterns for parameter binding. Both report significant readability wins for nested configuration types.
In compiler and parser code, AST traversal code uses record patterns to destructure nodes. The JavaParser library's visitor framework uses record patterns to inspect MethodCallExpr nodes, returning the callee, the method name, and the arguments in one expression. The Eclipse JDT compiler's AST visitor uses record patterns for the same purpose.
Conclusion
Java 16 record patterns (finalised in Java 21) extend the pattern-matching system to destructure records by their components, binding the values to fresh local variables in a single expression. Combined with nested patterns and pattern matching for switch, record patterns give Java a fully modern destructuring facility for algebraic data types. Next, study Java 21 pattern matching for switch to see the full pattern-matching system in action, and then read up on Java 21 virtual threads for high-throughput concurrency built on the same ergonomic philosophy.
Comments
Comments
Post a Comment