0Pricing
Java Academy · Lesson

Nested Record Patterns

Match deeply nested data.

Nested Record Patterns

Record patterns can nest: a component that is itself a record can be destructured inside the outer pattern. This matches deeply structured data in one expression.

A Nested Data Model

Consider a Line made of two Point records. The inner records are natural candidates for nesting.

public class Main {
    record Point(int x, int y) {}
    record Line(Point start, Point end) {}

    public static void main(String[] args) {
        Line line = new Line(new Point(0, 0), new Point(3, 4));
        System.out.println(line);
    }
}

All lessons in this course

  1. Pattern Matching for instanceof
  2. Record Patterns
  3. Nested Record Patterns
  4. Patterns in switch
← Back to Java Academy