Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Nested Record Patterns Explained

Learn how Java nested record patterns can deconstruct complex records safely and concisely in a single pattern, with syntax examples, switch usage, and limitations.

~4 min readJava
#Java#Record Patterns#Pattern Matching#Deconstruction
Diagram showing a Java record containing a nested record being deconstructed into its fields by a pattern matching arrow

Java nested record patterns let you deconstruct a record and its nested records in a single pattern, reducing the amount of boilerplate needed to inspect complex data structures. This article explains the syntax, shows practical examples, and covers the limitations you'll encounter when using them. The examples in this article use record patterns and pattern matching for switch, both final in Java 21.

What Nested Record Patterns Solve

Before record patterns, extracting fields from a record meant calling accessor methods and manually checking types. With nested records, that quickly becomes repetitive and error-prone. Consider a Point record inside a Shape record. To get the coordinates of a Circle shape, you'd write multiple lines of code, each with its own null check or cast. Nested record patterns collapse that into one declarative pattern that the compiler verifies.

Record Patterns and Deconstruction Basics

A record pattern matches a record type and binds its components to variables. For a record Point(int x, int y), a pattern looks like Point(int x, int y). When used with instanceof, it both checks the type and extracts the fields in one step:

java
record Point(int x, int y) {} if (obj instanceof Point(int x, int y)) { System.out.println(x + ", " + y); }

The variables x and y are in scope inside the if block in this example. This is the foundation for nesting.

Nesting Patterns Inside Other Patterns

A record pattern can appear inside another record pattern. For example, if a Circle record contains a Point center and a radius:

java
record Circle(Point center, int radius) {}

You can match a Circle and deconstruct its center in the same pattern:

java
if (obj instanceof Circle(Point(int x, int y), int r)) { System.out.println("Center: " + x + "," + y + " radius: " + r); }

The pattern Circle(Point(int x, int y), int r) matches only when obj is a Circle and its center is a Point. If center is null, the pattern fails to match because the nested pattern requires a non-null Point. This behavior is consistent with how record patterns handle null: the top-level pattern also fails if the object is null.

The nested pattern does not have to be the same type as the record component's declared type. If Circle had a Shape center component and Point were a subtype of Shape, the pattern Circle(Point(int x, int y), int r) would still compile and match when the center is actually a Point. The nested pattern adds the subtype test as part of the match.

Using Nested Record Patterns in Switch

Nested record patterns are especially useful in switch expressions and statements. The switch can select on the type and deconstruct nested data directly in each case:

java
record Point(int x, int y) {} record Line(Point start, Point end) {} record Circle(Point center, int radius) {} String describe(Object shape) { return switch (shape) { case Line(Point(int x1, int y1), Point(int x2, int y2)) -> "Line from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")"; case Circle(Point(int x, int y), int r) -> "Circle at (" + x + "," + y + ") radius " + r; default -> "Unknown shape"; }; }

This is more readable than a chain of instanceof checks and explicit casts. A switch expression must be exhaustive. For a selector of type Object, as in this example, that means you need a default case. For a sealed type, covering all permitted subtypes is also exhaustive.

Guarded Patterns and Conditions

You can add a guard to a nested record pattern using when. This allows you to apply additional conditions after the pattern matches. For example, to match only circles with a positive radius:

java
case Circle(Point(int x, int y), int r) when r > 0 -> "Circle at (" + x + "," + y + ") with positive radius";

The guard is evaluated only after the pattern matches successfully. If the guard fails, the switch continues to the next case. This keeps the logic inline and avoids separate if statements inside the case body.

Common Pitfalls and Limitations

Nested record patterns have a few constraints worth knowing. First, every component of a record pattern must contain a nested pattern; you cannot omit a component. If you need to bind a component but not inspect it, use a type pattern such as Circle(Point p, int r). If you want to ignore a component entirely, use the unnamed pattern _ when your JDK supports it (previewed in Java 21, finalized in Java 22): Circle(Point(int x, int y), _).

Second, a nested pattern's type must be compatible with the declared component type. You can use a more specific type than the component declaration; the pattern performs the subtype test. For example, if Circle had a Shape center component and Point implemented Shape, Circle(Point(int x, int y), int r) would work. If a component's runtime object is not a record, you cannot deconstruct it; use a type pattern to bind the value and inspect it further.

Third, null handling is strict. A record pattern never matches a null reference. If your data can contain nulls, you need to handle that explicitly, either with a null case in a switch or by checking before the pattern match.

Performance and Maintainability Considerations

Record patterns are a compile-time feature. They do not add runtime overhead beyond the equivalent manual type checks and casts. The JVM does not allocate extra objects for the deconstructed fields; the variables are bound directly to the record components. This means you can use nested patterns freely in performance-sensitive code without worrying about hidden allocations.

From a maintainability perspective, nested record patterns make the shape of the data visible at the point of use. When a record's structure changes, the compiler flags every pattern that no longer matches, which is safer than relying on reflective access or manual casting. However, deeply nested patterns can become hard to read. If you find yourself matching three or four levels deep, consider extracting a helper method or using a sealed interface hierarchy to simplify the pattern.

A practical balance is to use nested patterns for two or three levels of nesting, and to rely on guards for additional conditions rather than adding more nested patterns. This keeps the code readable while still taking advantage of the concise deconstruction that Java nested record patterns provide.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.