Record patterns: destructuring arrives
Match a record and pull its components apart in a single step, including nested ones.
Open this lesson in the learning hubKey points
- JEP 440 lets a pattern name the components:
case Point(int x, int y). - Patterns nest, so you can destructure a record inside a record in one line.
- It only works on records, because only records publish a guaranteed component order.
varworks inside a pattern when the type is obvious:case Point(var x, var y).- This is what turns sealed hierarchies into a genuinely usable alternative to the visitor pattern.
Example
public class Main {
sealed interface Shape permits Circle, Rect { }
record Point(int x, int y) { }
record Circle(Point centre, double r) implements Shape { }
record Rect(Point topLeft, Point bottomRight) implements Shape { }
static String origin(Shape s) {
return switch (s) {
// nested destructuring: reach straight into Point
case Circle(Point(var x, var y), var r) -> "circle at " + x + "," + y + " r=" + r;
case Rect(Point(var x1, var y1), Point(var x2, var y2)) ->
"rect " + (x2 - x1) + "x" + (y2 - y1) + " from " + x1 + "," + y1;
};
}
public static void main(String[] args) {
System.out.println(origin(new Circle(new Point(3, 4), 2.5)));
System.out.println(origin(new Rect(new Point(0, 0), new Point(10, 5))));
// Also works with instanceof
Object o = new Circle(new Point(1, 1), 9);
if (o instanceof Circle(Point p, double radius)) {
System.out.println("instanceof pattern: p=" + p + " radius=" + radius);
}
}
}
Record patterns replace a type check followed by a chain of accessors with one readable line.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 21 Course course, and every lesson in it is listed on the Java 21 Course contents page.