Destructuring

suggest change

Destructuring is the process of breaking down a composite data structure into its individual constituent variables. In modern Java (standardized in Java 21 via JEP 440), destructuring is achieved through Record Patterns, enabling developers to unpack record components directly within instanceof checks and switch expressions.

Record Patterns and instanceof

Before record patterns, unpacking an object required an instanceof type test, a cast, and individual calls to accessor methods. With record patterns, you can match the structure and bind variables in a single expression.

Consider a Point record:

public record Point(int x, int y) {}

Traditional Approach (Pre-Java 21)

public void printPoint(Object obj) {
    if (obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        System.out.println("Point at: " + x + ", " + y);
    }
}

Record Pattern Destructuring (Java 21+)

public void printPoint(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        // Variables x and y are extracted and directly available in scope
        System.out.println("Point at: " + x + ", " + y);
    }
}

You can also use type inference with var:

if (obj instanceof Point(var x, var y)) {
    System.out.println("Point at: " + x + ", " + y);
}

Nested Record Destructuring

Record patterns can be nested arbitrarily deep, allowing complex hierarchical data structures to be extracted in one clean statement:

public record ColoredPoint(Point point, String color) {}
public record Window(ColoredPoint topLeft, ColoredPoint bottomRight) {}

public void printWindowTopLeft(Object obj) {
    if (obj instanceof Window(ColoredPoint(Point(int x, int y), String color), var br)) {
        System.out.printf("Window top-left is at (%d, %d) with color %s%n", x, y, color);
    }
}

Destructuring in switch Expressions

Destructuring patterns shine in switch expressions, especially when paired with sealed interfaces to model algebraic data types:

public sealed interface Shape permits Circle, Rectangle, Triangle {}

public record Point(double x, double y) {}
public record Circle(Point center, double radius) implements Shape {}
public record Rectangle(Point topLeft, Point bottomRight) implements Shape {}
public record Triangle(Point a, Point b, Point c) implements Shape {}

You can switch on a Shape and destructure each subtype directly:

public static double calculateArea(Shape shape) {
    return switch (shape) {
        case Circle(Point(var x, var y), double r) ->
            Math.PI * r * r;

        case Rectangle(Point(var x1, var y1), Point(var x2, var y2)) ->
            Math.abs(x2 - x1) * Math.abs(y2 - y1);

        case Triangle(Point a, Point b, Point c) -> {
            // Heron's formula using vertices
            double sideA = Math.hypot(b.x() - a.x(), b.y() - a.y());
            double sideB = Math.hypot(c.x() - b.x(), c.y() - b.y());
            double sideC = Math.hypot(a.x() - c.x(), a.y() - c.y());
            double s = (sideA + sideB + sideC) / 2;
            yield Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
        }
    };
}

Guard Clauses with when

You can refine destructuring patterns using when guards:

public static String inspectPoint(Object obj) {
    return switch (obj) {
        case Point(var x, var y) when x == 0 && y == 0 -> "Origin";
        case Point(var x, var y) when x == 0 -> "On Y-axis at " + y;
        case Point(var x, var y) when y == 0 -> "On X-axis at " + x;
        case Point(var x, var y) -> "Point(" + x + ", " + y + ")";
        default -> "Not a point";
    };
}

Destructuring in Enhanced For Loops

Record patterns directly in enhanced for loops (for (Point(var x, var y) : points)) were previewed in Java 20 (JEP 432) but removed in Java 21, so that syntax does not compile in current Java. Destructure inside the loop body instead:

List<Point> points = List.of(new Point(0, 1), new Point(2, 3));

for (Point p : points) {
    if (p instanceof Point(var x, var y)) {
        System.out.printf("x = %d, y = %d%n", x, y);
    }
}

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents