• Home
  • About
    • Thoughts To Pen photo

      Thoughts To Pen

      My thoughts on Computer Programming || Psychology || Personal Finances || & much more...

    • Learn More
    • Twitter
    • Instagram
    • Github
    • StackOverflow
  • Posts
    • All Posts
    • All Tags
  • Projects
  • Portfolio
  • Resources
  • About

Record Patterns (Java 21)

20 Oct 2023

Record Patterns in Java 21

Record Patterns (JEP 440) have officially graduated from preview to a standard feature in Java 21. This feature significantly upgrades how we handle data in Java, specifically when working with Records.

What is a Record Pattern?

In simple terms, a Record Pattern allows you to “deconstruct” or “unpack” a Record object into its individual components directly.

Think of it as the opposite of creating an object. When you create a new Point(10, 20), you are packing two integers into a Point object. With Record Patterns, you can unbox those values back into two separate integer variables in a single step.

The Problem: Verbose Data Extraction

Before Java 21, extracting data from an object was a three-step process:

  1. Check the type (is this a Point?).
  2. Cast the object to that type (turn obj into Point p).
  3. Access the fields (call p.x() and p.y()).
record Point(int x, int y) {}

static void printSum(Object obj) {
    // Old Style: Check, Cast, Access
    if (obj instanceof Point p) {
        int x = p.x();
        int y = p.y();
        System.out.println(x + y);
    }
}

This acts as “boilerplate” code—it’s repetitive and adds noise to your logic.

The Solution: Clean Deconstruction

With Record Patterns, you can combine all three steps into one. When you ask instanceof Point(int x, int y), Java does the following for you:

  1. Checks if obj is a Point.
  2. If it is, it extracts the x and y values.
  3. It assigns them to new variables int x and int y that you can use immediately.
static void printSum(Object obj) {
    // New Style: Check & Extract in one line
    if (obj instanceof Point(int x, int y)) {
        System.out.println(x + y);
    }
}

This makes your code much easier to read because it focuses on what you normally do with data—use it!

Powerful Nested Patterns

The real power of Record Patterns appears when you have records inside other records. Imagine a ColoredPoint that contains a Point and a Color.

accessing the ‘x’ coordinate of a colored point used to involve a chain of accessors: coloredPoint.p().x().

Now, you can drill down deep into the structure in one go:

record Point(int x, int y) {}
record ColoredPoint(Point p, Color c) {}
enum Color { RED, GREEN, BLUE }

static void printColorPoint(Object obj) {
    // Nested Extraction
    if (obj instanceof ColoredPoint(Point(int x, int y), Color c)) {
        // We have direct access to 'x', 'y' and 'c' here!
        System.out.println("Point at (" + x + ", " + y + ") has color " + c);
    }
}

This is called Composition. You are composing patterns together to match complex data structures. It makes traversing data trees (like JSON-like structures, ASTs, or geometric shapes) incredibly distinct and declarative.

Summary

  • Less Boilerplate: No more casting or calling .get() or accessor descriptors manually.
  • Readable: The code looks like the data structure it is processing.
  • Declarative: You state what the data should look like, and Java handles the extraction.


programmingjavajava21 Share Tweet Msg