Records: nested destructuring reads a whole shape at once

Record patterns nest, so one case label can match an outer record and its inner records together, binding every component it needs.

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

Object obj = new Line(new Point(0, 0), new Point(3, 4));

switch (obj) {
    case Line(Point(var x1, var y1), Point(var x2, var y2)) -> {
        double len = Math.hypot(x2 - x1, y2 - y1);
        System.out.println("from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")");
        System.out.println("length = " + len);
    }
    default -> System.out.println("not a line");
}
Output
from (0,0) to (3,4)
length = 5.0
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30