Sub topic 8
Records as the data side of pattern matching
Pattern matching needs two sides. The control side is instanceof and switch. The data side is a kind of type whose shape the compiler can see. In Java, records are that data side. This chapter explains what a record guarantees and which of those guarantees pattern matching relies on. It also covers the mistakes that break the guarantees.
This chapter assumes you know Java classes, interfaces and basic generics. You should also be able to read a switch expression. You need JDK 21 or newer to run the examples.
What a record declares
A record is a class whose state is fully described by a header. The header lists the record's components.
public class RecordBasics {
record Point(int x, int y) {}
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p);
System.out.println(p.x());
System.out.println(p.equals(new Point(3, 4)));
}
}This prints Point[x=3, y=4], then 3, then true.
From the header (int x, int y) the compiler generates four things:
- A private final field for each component.
- A canonical constructor that takes the components in header order.
- An accessor method for each component. The accessor is named after the component, so it is
x()and notgetX(). equals,hashCodeandtoString, all computed from the components.
Two records with equal components are equal. A record has no identity beyond its data. That is why it suits pattern matching: the matcher can treat a Point as "an x and a y" and nothing else.
Why "transparent" matters
A record is a transparent carrier. The header is a public statement that the type is nothing more than these components, in this order. A normal class can hide its fields, store derived values, or change its representation freely. A record cannot.
That commitment is what lets the language add deconstruction. A record pattern names the type and then the components:
public class RecordPatternPreview {
record Point(int x, int y) {}
public static void main(String[] args) {
Object o = new Point(3, 4);
if (o instanceof Point(int x, int y)) {
System.out.println(x + y);
}
}
}This prints 7. The next chapter covers record patterns in detail. For now, notice what the pattern depends on. The compiler knows Point has exactly two components, int x and int y, in that order. It can check the pattern's shape at compile time. A pattern such as Point(int x) is a compile-time error because the component count is wrong.
An ordinary class gives the compiler no such information. Even if it has a constructor with two parameters and two getters, nothing says those getters correspond to the constructor parameters.
| Property | Ordinary class | Record |
|---|---|---|
| State described by | Fields chosen by the author | The header components |
| Component list is public API | No | Yes |
| Usable in a record pattern | No | Yes |
| Can extend another class | Yes | No (extends `java.lang.Record`) |
| Can implement interfaces | Yes | Yes |
| Instance fields beyond components | Yes | No |
| Fields are final | Optional | Always |
How a record pattern reads the data
When a record pattern matches, Java first checks the type. It then calls each accessor and matches the returned value against the sub-pattern for that component. The pattern does not read the private fields directly. It goes through the accessor methods.
This has two consequences:
- If you override an accessor, the pattern sees the overridden result.
- If an accessor throws an exception, the match does not simply fail. The exception is wrapped in a
MatchException. A later chapter covers this failure mode.
An accessor override must be public, return the component's type, and declare no checked exceptions. In practice, leave accessors alone. A pattern is supposed to see the same data as equals and toString, and an accessor that returns something different breaks that expectation.
Validating and normalizing in a compact constructor
The canonical constructor is the one place to enforce invariants. The compact form omits the parameter list and the field assignments. The compiler assigns the fields at the end of the constructor body.
public class RangeDemo {
record Range(int low, int high) {
Range {
if (low > high) {
throw new IllegalArgumentException(
"low > high: " + low + " > " + high);
}
}
}
public static void main(String[] args) {
System.out.println(new Range(1, 5));
try {
new Range(5, 1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}The program prints Range[low=1, high=5] and then low > high: 5 > 1.
Validation matters for pattern matching because patterns make every instance trustworthy. If every Range is guaranteed to satisfy low <= high, code that deconstructs a Range can rely on it without rechecking.
You can also reassign the parameters in a compact constructor to normalize them:
public class EmailDemo {
record Email(String value) {
Email {
value = value.strip().toLowerCase();
}
}
public static void main(String[] args) {
Object o = new Email(" [email protected] ");
if (o instanceof Email(String v)) {
System.out.println(v);
}
}
}This prints [email protected]. Normalization happens in the constructor, so the pattern sees the normalized value. Assign to the parameter (value = ...), not to this.value. Assigning to a field in a compact constructor is a compile-time error.
Records are only shallowly immutable
The fields of a record are final, but that does not make the objects they point to immutable. A record holding a List or an array can still change under you. Pattern matching hands out the same reference, not a copy.
import java.util.ArrayList;
import java.util.List;
public class PlaylistDemo {
record Playlist(String name, List<String> tracks) {
Playlist {
tracks = List.copyOf(tracks);
}
}
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("a", "b"));
Playlist p = new Playlist("mix", source);
source.add("c");
System.out.println(p.tracks());
}
}This prints [a, b]. Without List.copyOf, it would print [a, b, c], because the record would share the caller's list. Copy mutable inputs in the compact constructor. List.copyOf also rejects null elements and returns an unmodifiable list.
Arrays are worse. Record equals compares array components by reference, so two records holding equal arrays are not equal. Prefer a List for record components.
Records inside sealed hierarchies
Records are final, so they cannot be subclassed. That makes them natural leaves for a sealed interface. The sealed interface lists the possible shapes, and each record describes the data of one shape.
A switch over Shape can then work with both sides at once. The sealed interface tells the compiler which cases exist. Each record tells it what data each case carries. The following chapters build on this combination.
Records can have methods, static members and nested types. A record can also be declared locally, inside a method. This is useful for small, throwaway data shapes:
import java.util.List;
public class LocalRecordDemo {
public static void main(String[] args) {
record Pair(String word, int length) {}
List<Pair> pairs = List.of("pattern", "record").stream()
.map(w -> new Pair(w, w.length()))
.toList();
System.out.println(pairs);
}
}This prints [Pair[word=pattern, length=7], Pair[word=record, length=6]].
Common errors
- Adding an instance field.
record Point(int x, int y) { int z; }does not compile. Extra state would break transparency. Add a component or compute the value in a method. - Calling
getX(). The accessor isx(). Only a record with a hand-written method of that name would havegetX(). - Assigning
this.fieldin a compact constructor. This is a compile-time error. Assign to the parameter instead. - Expecting
nullto be rejected. Record components may be null unless your constructor forbids it. A pattern such asEmail(String v)matches anEmailwhosevalueis null. UseObjects.requireNonNullwhere null makes no sense. - Using a record where identity matters. Two records with equal components are interchangeable. If two objects with the same data must stay distinct, a record is the wrong choice.
- Exposing a type you may want to change. The header is permanent API. Adding or reordering components breaks every constructor call and every record pattern that uses the type.
Choosing a record
Use a record when the type is its data: coordinates, messages, tokens, tree nodes, results. Use a class when the type hides its representation, has mutable state, or needs identity. The test is simple. If you would be happy for every caller to see all the components, make it a record.
Exercise
A record Temperature(double degrees) has a compact constructor that rejects values below -273.15. A teammate says a record pattern Temperature(double d) could still produce a value below -273.15 for d. Is the teammate right, and what would you check?
Show answer
Not if every instance is created through the canonical constructor, because the check runs on every construction and the pattern only reads the accessor of an already-validated instance. The teammate could be right only if someone overrides the degrees() accessor to return a different value, or if the validation is missing from the canonical constructor (for example, it was added only to a secondary constructor that delegates elsewhere). Check that the compact constructor holds the validation and that no accessor is overridden.
Exercise
What does this code print, and why? record Tags(List<String> items) {} then var list = new ArrayList<>(List.of("a")); var t = new Tags(list); list.add("b"); System.out.println(t.items());
Show answer
It prints [a, b]. The record's field is final, but it holds a reference to the caller's mutable list, so changes made through list are visible through t.items(). A compact constructor with items = List.copyOf(items); fixes it, and the output would then be [a].