Lesson · Records, Sealed Types & Pattern Matching
Records: data carriers done right
16 min readRecords (Java 16+)
One line declares the components; the compiler writes the fields, constructor, accessors, equals, hashCode and toString. Compact constructors add validation and defensive copies, and records make excellent map keys.
The sixty lines that became one
A two-field value class traditionally means fields, constructor, accessors, equals, hashCode and toString by hand. The record declaration replaces all of it:
record Point(int x, int y) { } Point p = new Point(2, 3); System.out.println(p); // Point[x=2, y=3] System.out.println(p.x()); // 2: accessor, not getX() System.out.println(new Point(2, 3).equals(p)); // true
Predict: where did Point[x=2, y=3] and the working equals come from? The compiler generated both from the component list. A record is a class whose data is the whole declaration: components in, canonical members out, and an immutability promise on top.
What the compiler writes
For record Point(int x, int y), the generated members and the fixed rules:
| Generated | Shape | Note |
|---|---|---|
| Fields | private final int x, y | One per component, final |
| Canonical constructor | Point(int x, int y) | Runs your validations if you add a compact form |
| Accessors | x(), y() | Named after the component: no get prefix |
equals / hashCode | From every component | Value equality, exactly the contract from the equals lesson |
toString | Point[x=2, y=3] | Component names and values |
| Class modifiers | final, extends java.lang.Record | No subclassing, no extra instance fields |
- You may add more: static fields and methods, instance methods, additional constructors that delegate to the canonical one.
- You may not add: instance fields beyond the components, or an
extendsclause; the record shape is fixed so the generated members stay honest. - Shallow immutability: components are final, but a component pointing at a mutable object (a list) still leads to a mutable object.
`equals` and `hashCode` come as a correctly paired set. A record used as a HashMap key works the moment it is declared, which is the contracts chapter's whole checklist satisfied by the compiler.
Compact constructors: validation and the copy
The compact constructor takes no parameter list: it receives the components by name, and what you assign is what gets stored.
record Range(int low, int high) { Range { // compact form if (low > high) throw new IllegalArgumentException("low > high"); } } record Team(String name, List<String> members) { Team { members = List.copyOf(members); // the defensive copy lives here } }
- Validation:
new Range(5, 1)cannot exist; the invariant is enforced at the only moment it can be created. - Normalisation: assigning to the parameter (
x = Math.abs(x)) stores the corrected value; every accessor sees it. - The defensive copy closes the shallow-immutability gap: the component still points at a list, but at an immutable snapshot the caller cannot reach.
- The copy runs once per construction: reads stay allocation-free, and the record keeps its value semantics.
The canonical constructor is the single door. Records channel every construction through it, which is why validation here is total: there is no other path in.
Record anatomy · what one line generates
You write
The compiler writes
fields
private final int x, y;
canonical constructor
Point(int x, int y) { this.x = x; this.y = y; }
accessors
int x() { return x; } int y() { return y; }
equals / hashCode
generated from both components, correctly paired
toString
Point[x=2, y=3]
You write the declaration: a name and the components. Everything the compiler will add follows from this single line's shape.
Records as keys, values and results
Three places where the generated members earn their keep:
- Map keys: generated
equalsandhashCodeagree, so a record is a correct key by construction; keep components immutable and the hash stays stable while stored. - Multiple return values: a method returning
record Result(boolean ok, String message)replaces out-parameters and parallel arrays; destructure it with pattern matching later in the chapter. - Restrained data classes: DTOs, coordinates, ranges, API payloads; the record documents exactly which data is the identity, because the component list is the identity.
Records do not replace classes; they replace the boilerplate around data. When behaviour dominates, reach for a class; when data is the point, a record is the shortest path to correct.
The record playbook
Declaring data carriers, in order:
- List the components first; they are the type's public identity and its equality.
- Add a compact constructor the moment an invariant exists; validate and normalise there.
- Copy mutable components defensively in the compact constructor (
List.copyOf,Map.copyOf, array clone). - Keep behaviour in instance methods that read the components; static factories and constants are welcome.
- When you need extra instance state or inheritance, that is a class talking: records are for the shapes they fit.
One line declares the data; the compiler guarantees the rest. Equality, hashing, printing and immutability are the four things value types always need and casually get wrong, and a record gets right by construction.
A record is a name for its data
Components generate final fields, a canonical constructor, accessors without get, and correctly paired equals/hashCode plus toString. Compact constructors add validation, normalisation and defensive copies at the single door every construction goes through. Reach for a class when behaviour or extra state dominates; reach for a record whenever the data is the point.
Interview angles
What exactly does a record generate?+
Final fields for each component, the canonical constructor, accessors named after the components, equals and hashCode from all components, and a toString like Point[x=2, y=3]; the class is final and extends java.lang.Record.
The generator is not magic to memorise but a checklist to trust: the equals/hashCode pair is correctly matched, the equality is value-based, and the accessor names (x(), not getX()) are part of the record's design.
record Point(int x, int y) { } new Point(2, 3).equals(new Point(2, 3)); // true, generated
Common misconception: That records are simple beans. They are final value carriers with a compiler-enforced shape, not JavaBeans with conventions.
Follow-up: Which member would a JavaBean-style API expect that records deliberately do not generate?
What is a compact constructor for?+
Validation, normalisation and defensive copying: it sits in place of the canonical constructor, receives the components implicitly, and whatever it assigns is what gets stored.
Validation makes illegal instances impossible (the invariant is checked at the only door construction passes through). Defensive copying fixes the shallow-immutability gap for array or collection components: members = List.copyOf(members) snapshots and locks the value.
Team { members = List.copyOf(members); } // copy lives at the door
Common misconception: That a record with a mutable component is fully immutable. The reference is final; the referenced object needs the copy you did not write yet.
Follow-up: Where else could normalisation happen, and why is the constructor better?
Why do records make good map keys?+
Because the generated equals and hashCode are guaranteed consistent from the same component list, and the components are final: the two contracts hash structures rely on, satisfied by construction.
The contracts chapter's checklist (equal fields for both methods, stable fields while stored) is compiler-enforced, provided components are immutable. A record whose component holds a mutable list reopens the mutation trap inside its component, which one copyOf closes.
Map<Point, String> map = new HashMap<>(); map.put(new Point(2, 3), "here"); map.get(new Point(2, 3)); // here
Common misconception: That any data class works as a key. Designers must remember to pair equals and hashCode correctly; records cannot forget.
Follow-up: What breaks if a record component is a mutable array used as a key?
What are the limits of records?+
No extra instance fields beyond the components, no extends clause (records already extend java.lang.Record), no subclassing (they are final), and no instance field declarations at all; static members and instance methods are fine.
The restrictions are the point: with the component list as the only instance state, the generated equals/hashCode/toString can never drift from the data. Adding behaviour is allowed; adding hidden state is not.
record Point(int x, int y) { static Point origin() { return new Point(0, 0); } // fine // int z; // error: extra instance field }
Common misconception: That the limits make records weak. They make them precise: for value semantics, hidden state is a bug source, not a feature.
Follow-up: When does the need for extra state mean 'use a class'?
Local records? Nested records? Where can records live?+
Anywhere a class can: top level, nested (static by default; records are implicitly static nested), and even inside method bodies as local records, when a small value type belongs to one method.
Nested records make sealed hierarchies compact (each permitted subtype a record in the same file), and local records keep one-method helpers out of the package namespace. Records can also implement interfaces, including sealed ones, which is the bridge to the next lesson.
record Range(int low, int high) implements Comparable<Range> { public int compareTo(Range o) { return Integer.compare(low, o.low); } }
Common misconception: That records must be simple files of their own. They nest and implement interfaces like any type; only the instance-state shape is restricted.
Follow-up: Why are nested records implicitly static?