Skip to main content
Java 21 (LTS) · Topic 3 of 4

Record patterns

Definition​

A record pattern (Java 21) takes a record apart inside instanceof or switch, giving you its fields as variables. Patterns can be nested, so you can unpack a record that holds other records in one step.

Example code​

Unpacking a Line made of two Points

record Point(int x, int y) { }
record Line(Point from, Point to) { }

class Demo {
static String describe(Object shape) {
return switch (shape) {
case Point(int x, int y) -> "point at " + x + "," + y;
case Line(Point(var x1, var y1), Point(var x2, var y2)) // nested pattern
-> "line from " + x1 + "," + y1 + " to " + x2 + "," + y2;
default -> "unknown";
};
}

public static void main(String[] args) {
System.out.println(describe(new Point(1, 2)));
System.out.println(describe(new Line(new Point(0, 0), new Point(5, 5))));
}
}

// Output:
// point at 1,2
// line from 0,0 to 5,5

Finished this page? Track your progress (saved only in your browser).