0Pricing
Java Academy · Lesson

Nested Record Patterns

Match deeply nested data.

Nested Record Patterns is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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);
    }
}

One-Level Destructuring

A flat pattern binds the two Point components but leaves them whole.

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

    public static void main(String[] args) {
        Object obj = new Line(new Point(0, 0), new Point(3, 4));
        if (obj instanceof Line(Point s, Point e)) {
            System.out.println(s + " -> " + e);
        }
    }
}

Going Deeper

Replace the inner Point s with its own record pattern to reach the coordinates directly: Line(Point(int x1, int y1), Point(int x2, int y2)).

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

    public static void main(String[] args) {
        Object obj = new Line(new Point(0, 0), new Point(3, 4));
        if (obj instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) {
            double len = Math.hypot(x2 - x1, y2 - y1);
            System.out.println("Length: " + len);
        }
    }
}

Any Depth

Nesting can go as deep as your data. Each level either binds a whole component or destructures further, mirroring the shape of the structure exactly.

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

    public static void main(String[] args) {
        Object obj = new Drawing(new Line(new Point(1, 2), new Point(3, 4)), "diag");
        if (obj instanceof Drawing(Line(Point(var ax, var ay), var end), var label)) {
            System.out.println(label + " starts at " + ax + "," + ay);
            System.out.println("ends near " + end);
        }
    }
}

Mixing var and Types

Within a nested pattern you can freely mix explicit types and var. Use var for components you only pass along and explicit types where clarity helps.

Nesting in switch

Nested patterns are especially expressive in switch, letting each case describe a precise data shape.

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

    static String describe(Object o) {
        return switch (o) {
            case Line(Point(var x1, var y1), Point(var x2, var y2)) when x1 == x2 -> "vertical";
            case Line(Point p1, Point p2) -> "general line";
            default -> "not a line";
        };
    }

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

The Whole Match Must Hold

A nested pattern matches only if every level matches. If any component is a different type than its sub-pattern expects, the overall match fails and no variables are bound.

Readability Trade-Off

Deep nesting is powerful but can get hard to read. If a pattern grows too large, consider destructuring one level and handling the rest with separate logic.

Guards Over Nested Bindings

Because nested patterns expose inner values as locals, a single when guard can reference fields from several levels at once.

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

    static boolean isUnitStep(Object o) {
        return o instanceof Line(Point(int x1, int y1), Point(int x2, int y2))
            && x2 - x1 == 1 && y2 - y1 == 1;
    }

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

A Complete Example

Compute the midpoint of a line by destructuring both endpoints.

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

    static Point midpoint(Object o) {
        if (o instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) {
            return new Point((x1 + x2) / 2, (y1 + y2) / 2);
        }
        return null;
    }

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

Quick Check

Test your understanding of nested record patterns.

Recap

You learned nested record patterns.

  • A record component that is itself a record can be destructured inline.
  • Nesting can go to any depth and mix explicit types with var.
  • The match succeeds only if every level matches.
  • Inner bindings are usable in guards and the body together.

Frequently asked questions

Is the “Nested Record Patterns” lesson free?

Yes — the full text of “Nested Record Patterns” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Nested Record Patterns”?

Match deeply nested data. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Nested Record Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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