Sub topic 8
Records as the Data Side of Pattern Matching
Prerequisites
This chapter assumes you know Java classes, interfaces, inheritance, and basic generics. You should also know how to write switch expressions and use instanceof. The examples use Java 21 or newer.
Pattern matching works best when the data has a clear shape. A Java record is a compact class for carrying data. Its components define that shape.
record Point(int x, int y) {}This declaration creates a final class with:
- Two private final fields,
xandy. - Accessor methods named
x()andy(). - A constructor accepting both values.
equals,hashCode, andtoStringimplementations.
The accessor names do not use the usual getX() form. You call point.x() and point.y().
Records are useful because their data is visible in their declaration. Pattern matching can use that declaration to take a record apart.
Records Are Transparent Data Carriers
A record is mainly a description of data, not a container for changing state. Its fields cannot be reassigned after construction.
record Rectangle(double width, double height) {
Rectangle {
if (width < 0 || height < 0) {
throw new IllegalArgumentException("dimensions must be non-negative");
}
}
double area() {
return width * height;
}
}The compact constructor validates the components before the record is created. The area method is allowed because records can contain behavior. However, a record is usually a good fit when its identity is based on its data.
The immutability is shallow. A record component can refer to a mutable object:
record Report(java.util.List<String> lines) {}The Report reference cannot change, but the list may still change. Copy mutable inputs when the record must protect its contents.
Record Patterns Read the Components
A record pattern matches a record and binds its components to local variables.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
public class RecordPatternDemo {
static String describe(Object value) {
return switch (value) {
case Point(int x, int y) -> "point (" + x + ", " + y + ")";
case Line(Point start, Point end) ->
"line from " + start + " to " + end;
default -> "other value";
};
}
public static void main(String[] args) {
System.out.println(describe(new Point(3, 4)));
System.out.println(describe(new Line(
new Point(0, 0),
new Point(5, 5))));
}
}Point(int x, int y) is a record pattern. It checks that the value is a Point, calls its accessors, and binds the results to x and y. Without a record pattern, you would first match the type and then call x() and y() manually.
A record pattern does not create a copy. It reads the existing record's components.
Choosing Records for Pattern Matching
Use a record when:
- The type primarily represents data.
- Its components form the type's identity.
- Construction-time validation is enough.
- Consumers benefit from inspecting its fixed shape.
Use a regular class when the# Records as the Data Side of Pattern Matching
This chapter assumes you know Java classes, interfaces, inheritance, switch expressions, instanceof, and basic generics. It also assumes JDK 21 or newer. Records are the data representation that makes record patterns useful: patterns can match a record and read its components without calling accessors separately.
What a record provides
A record is a compact class declaration for a fixed group of values. Java generates the following members automatically:
- A private, final field for each component.
- A public accessor with the component's name.
- A canonical constructor that initializes all components.
equals,hashCode, andtoStringmethods.
record Point(int x, int y) {}
public class RecordDemo {
public static void main(String[] args) {
Point point = new Point(3, 4);
System.out.println(point.x());
System.out.println(point.y());
System.out.println(point);
}
}The declaration creates a Point value with components named x and y. The accessor is x(), not getX(). The generated toString prints a useful representation such as Point[x=3, y=4].
A record is still a class. It can implement interfaces, define methods, and validate its input. It cannot extend another class, because every record already extends java.lang.Record.
Records are transparent data carriers
A regular class may hide its internal representation behind methods. A record makes its components part of its public API. This transparency is useful when a program's logic depends on the shape of its data.
record Temperature(double celsius) {
Temperature {
if (!Double.isFinite(celsius)) {
throw new IllegalArgumentException("temperature must be finite");
}
}
boolean isFreezing() {
return celsius <= 0;
}
}The compact constructor validates the component before the generated assignments run. The record prevents reassignment of the component reference, but this is shallow immutability. For example, a record containing a List<String> cannot replace its list reference, but the list itself may still be mutable.
Why records fit pattern matching
Without record patterns, code must test the type and then call accessors:
static String describe(Object value) {
if (value instanceof Point point) {
return "point at (" + point.x() + ", " + point.y() + ")";
}
return "other value";
}The type pattern binds the Point, but the method still reads each component explicitly. A record pattern can later combine the type test and component extraction in one expression:
static String describe(Object value) {
return switch (value) {
case Point(int x, int y) -> "point at (" + x + ", " + y + ")";
default -> "other value";
};
}The pattern Point(int x, int y) checks that the value is a Point, calls its accessors, and binds the returned values to x and y. The record declaration defines the component order used by this deconstruction.
Choosing a record or a class
| Requirement | Better choice |
|---|---|
| Equality should be based on all declared values | Record |
| The object has stable identity independent of its fields | Class |
| The public data shape should be visible | Record |
| The representation must change without affecting callers | Class |
A record does not replace every data class. Choose a regular class when you need mutable state, inheritance from another class, hidden representation, or identity-based behavior.
Exercise
What does the pattern Point(int x, int y) do when it matches a Point value?
Show answer
It checks the value's type, calls x() and y(), and binds the results to the pattern variables x and y.