Cut Java 21 Record Pattern Matching Code in Half

This article demonstrates how Java 21's switch pattern matching and record deconstruction let you replace verbose instanceof checks with concise two‑line snippets, even for nested records, dramatically simplifying code that extracts fields from complex objects.

Programmer DD
Programmer DD
Programmer DD
Cut Java 21 Record Pattern Matching Code in Half

Java 21 introduces switch pattern matching and record deconstruction, allowing developers to replace lengthy instanceof checks with concise code.

record Point(int x, int y) {}

static void printSum(Object obj) {
    if (obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        System.out.println(x + y);
    }
}

Before Java 21, extracting the fields of a Point required four lines of code; with pattern matching it can be done in just two lines:

static void printSum(Object obj) {
    if (obj instanceof Point(int x, int y)) {
        System.out.println(x + y);
    }
}

In real projects records are often nested. Consider the following records:

record Size(int width, int height) {}
record Point(int x, int y) {}
record WindowFrame(Point origin, Size size) {}

To print the height of the Size inside a WindowFrame the traditional approach would be:

if (obj instanceof WindowFrame wf) {
    if (wf.size() != null) {
        System.out.println("Height: " + wf.size().height());
    }
}

Java 21 allows nested deconstruction, reducing the above to a single check:

if (obj instanceof WindowFrame(Point origin, Size(int width, int height))) {
    System.out.println("Height: " + height);
}

The image below illustrates the record hierarchy used in the examples.

Record hierarchy diagram
Record hierarchy diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentJava 21pattern-matchingrecord patterns
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.