Data with a fixed set of shapes
A payment arriving at a shop in Nairobi might be a card payment (with a network and the last four digits), a mobile-money payment (with a phone number), or a bank transfer (with an account and a flag saying whether it crossed a border). Those are the only three kinds the business accepts. Each kind carries different data, and the fee rules depend on the kind and on the data inside it.
How should Java code represent this? The classic object-oriented answer is a Payment interface with a fee() method that each class implements. That works well when new kinds of payment arrive often. But businesses usually add new questions far more often than new kinds: today fees, tomorrow fraud checks, next week a monthly report, each one written by a different team. Spreading every question across every class makes each class a grab bag of unrelated concerns.
Modern Java offers a second style, often called data-oriented programming. You model the data as plain, immutable values (records), you state the full list of alternatives (sealed types), and you write each question as one function that takes the data apart with pattern matching. The compiler knows the list of alternatives, so it can tell you when a function forgets one. Languages such as ML, Haskell, Rust, Scala and Kotlin have worked this way for a long time; Java adopted it between JDK 16 and JDK 21 through Project Amber.
Definitions
Definition— Record
A class declared as record Name(Type a, Type b) { ... } whose state is exactly its components. Java generates a private final field for each component, a canonical constructor, an accessor method for each (a(), not getA()), and equals, hashCode and toString based on all components. A record is implicitly final, cannot extend a class, and cannot declare instance fields beyond its components; it can implement interfaces and declare methods, static fields and nested types. Final in JDK 16.
Definition— Compact constructor
A constructor written without a parameter list, Name { ... }, that runs before the fields are assigned. It can validate the parameters, and can reassign them (for example, to normalise or copy) before they are stored.
Definition— Enum
A type with a fixed set of named instances: enum Network { VISA, MASTERCARD, RUPAY }. Enums can have fields, constructors and methods, and are the simplest way to say "one of these constants".
Definition— Sealed class or interface
A type that lists the only classes allowed to extend or implement it, with permits (which may be omitted when they are all in the same file). Each permitted subclass must be final (records are), sealed again, or explicitly non-sealed. Final in JDK 17.
Definition— Pattern
A test that, when it matches, also binds variables. A type pattern Card c matches a Card and names it c. A record pattern Card(var network, _, long cents) matches a Card and extracts its components; patterns nest. A guard when condition adds a further test. _ is an unnamed pattern for parts you do not need (JDK 22).
Definition— Exhaustiveness
A switch expression, and any switch that uses patterns, must cover every possible value of its selector. For a sealed type, covering every permitted subtype is enough, with no default.
In type-theory terms, a record is a product type (a value has all of its components) and a sealed interface over records is a sum type (a value is exactly one of the alternatives). Together they are what functional programmers call algebraic data types.
Records: data that means what it says
import java.util.ArrayList;
import java.util.List;
public class Main {
/** A geographic point. Latitude and longitude in degrees. */
record Location(double lat, double lon) {
Location { // compact constructor: validates the components
if (lat < -90 || lat > 90) {
throw new IllegalArgumentException("latitude out of range: " + lat);
}
if (lon < -180 || lon > 180) {
throw new IllegalArgumentException("longitude out of range: " + lon);
}
}
}
/** A delivery route: a name and the stops in order. */
record Route(String name, List<Location> stops) {
Route {
name = name.strip(); // normalise a component before it is stored
stops = List.copyOf(stops); // defensive, unmodifiable copy
}
int size() { // records can have ordinary methods
return stops.size();
}
Route withName(String newName) { // a "wither": a changed copy, not a mutation
return new Route(newName, stops);
}
}
public static void main(String[] args) {
var dakar = new Location(14.69, -17.45);
var same = new Location(14.69, -17.45);
System.out.println(dakar);
System.out.println("equal: " + dakar.equals(same) + ", same object: " + (dakar == same));
System.out.println("hash codes match: " + (dakar.hashCode() == same.hashCode()));
System.out.println("latitude: " + dakar.lat());
List<Location> stops = new ArrayList<>(List.of(dakar, new Location(14.79, -16.93)));
Route route = new Route(" coast run ", stops);
stops.add(new Location(0, 0)); // changing the caller's list...
System.out.println(route.name() + " has " + route.size() + " stops"); // ...does not change the record
System.out.println(route.withName("express").name());
try {
new Location(95, 0);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}Location[lat=14.69, lon=-17.45]
equal: true, same object: false
hash codes match: true
latitude: 14.69
coast run has 2 stops
express
latitude out of range: 95.0Two lines of declaration bought a constructor, accessors, a readable toString, and equals and hashCode that compare by value. Two Locations with the same coordinates are equal, so they work correctly as keys in a HashMap or members of a HashSet. Writing those methods by hand for a class with five fields takes about fifty lines and is a well-known source of bugs; with records, the compiler writes them and keeps them in step with the components.
The compact constructors show the three jobs a record's constructor usually has:
- Validate: an impossible latitude never becomes a
Location. EveryLocationthat exists anywhere in the program is valid, so no other code needs to check. - Normalise:
name = name.strip()reassigns the parameter; the field is assigned from it after the compact constructor finishes. - Copy defensively: a record's fields are final, but a
Listfield could still be a mutable list that the caller keeps changing.List.copyOfmakes the record's own unmodifiable copy, so the laterstops.add(...)had no effect onroute. Without it, the record would be immutable only on the surface ("shallowly immutable").
Records are not the right tool for everything. Use them for values whose identity does not matter: coordinates, money amounts, messages, results, keys, configuration. An entity with a lifecycle and changing state (an open bank account, a game character) is better as an ordinary class.
Sealed types and switch patterns
Now the payments. The sealed interface lists the three alternatives; each alternative is a record; and the questions are switch expressions.
import java.util.Arrays;
import java.util.List;
public class Main {
enum Network { VISA, MASTERCARD, RUPAY }
sealed interface Payment permits Card, MobileMoney, BankTransfer {}
record Card(Network network, String last4, long cents) implements Payment {}
record MobileMoney(String phone, long cents) implements Payment {}
record BankTransfer(String account, long cents, boolean international) implements Payment {}
/** The processing fee in cents. No default branch: the compiler checks every case is covered. */
static long fee(Payment p) {
return switch (p) {
case Card(Network n, _, long cents) when n == Network.RUPAY -> cents / 200; // 0.5%
case Card(_, _, long cents) -> cents * 3 / 200; // 1.5%
case MobileMoney(_, long cents) -> Math.min(cents / 100, 500); // 1%, at most 5.00
case BankTransfer(_, _, boolean international) when international -> 1500;
case BankTransfer _ -> 0;
};
}
static String describe(Payment p) {
return switch (p) {
case Card c -> c.network() + " card ending " + c.last4();
case MobileMoney m -> "mobile money from " + m.phone();
case BankTransfer t -> (t.international() ? "international" : "domestic") + " transfer";
};
}
public static void main(String[] args) {
List<Payment> today = List.of(
new Card(Network.VISA, "4242", 10_000),
new Card(Network.RUPAY, "1881", 10_000),
new MobileMoney("+254700000001", 80_000),
new BankTransfer("0012-3456", 250_000, true),
new BankTransfer("0098-7654", 250_000, false));
long total = 0;
for (Payment p : today) {
long f = fee(p);
total += f;
System.out.printf("%-36s fee %5d%n", describe(p), f);
}
System.out.println("total fees: " + total);
// Enums know their constants, in declaration order
System.out.println(Arrays.toString(Network.values()) + " " + Network.valueOf("RUPAY").ordinal());
// instanceof with a record pattern: test, destructure and bind in one step
Object o = today.getFirst();
if (o instanceof Card(var network, _, var cents) && cents > 5_000) {
System.out.println("large card payment on " + network);
}
}
}VISA card ending 4242 fee 150
RUPAY card ending 1881 fee 50
mobile money from +254700000001 fee 500
international transfer fee 1500
domestic transfer fee 0
total fees: 2200
[VISA, MASTERCARD, RUPAY] 2
large card payment on VISAHow the fee switch is evaluated:
- Cases are tried from top to bottom, and the first match wins. That is why the guarded
Card ... when n == Network.RUPAYcomes before the unguardedCard(_, _, long cents). If you put them the other way round, the compiler reports that the second case is dominated (it can never match) and refuses to compile. - Record patterns deconstruct.
Card(Network n, _, long cents)checks thatpis aCard, then binds its first and third components;_ignores the second. You may write the component types, orvarto let the compiler infer them. - Guards (
when international) refine a pattern with any boolean condition, using the variables the pattern bound. - No
default. The selector's type is sealed, and every permitted subtype has an unguarded case (Card(_, _, long cents),MobileMoney(...),BankTransfer _), so the switch is exhaustive and the compiler accepts it.
describe uses simple type patterns (case Card c), which are often clearer than deconstruction when you need only one or two components. And the last lines show patterns outside switch: o instanceof Card(var network, _, var cents) && cents > 5_000 tests the type, extracts the components and uses them in one condition. Before JDK 16 that took an instanceof, a cast and two method calls.
Network is an enum. values() lists its constants in declaration order, valueOf looks one up by name, and ordinal() gives its position. Enums work in switch with exhaustiveness checking too. Use them for fixed sets of constants; use a sealed interface when the alternatives carry different data.
The safety net
Suppose the business starts accepting vouchers, and someone adds Voucher to the permits list. Every switch over Payment without a default now fails to compile, each with an error like this one (from removing a case from describe):
Main.java:7: error: the switch expression does not cover all possible input values
return switch (p) {
^That is a gift. The compiler has found every place that must decide what a voucher means, before any customer pays with one. A default branch would have silently swallowed the new case. Avoid default in switches over sealed types unless "everything else" genuinely has one meaning.
Nested patterns: a tiny algebra system
Patterns nest, which makes tree-shaped data a pleasure to work with. Here is a sealed hierarchy of arithmetic expressions, with three functions written as switches: evaluate, simplify and display.
sealed interface Expr {}
record Num(int value) implements Expr {}
record Var(String name) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
int eval(Expr e, int x) {
return switch (e) {
case Num(int v) -> v;
case Var _ -> x;
case Add(Expr l, Expr r) -> eval(l, x) + eval(r, x);
case Mul(Expr l, Expr r) -> eval(l, x) * eval(r, x);
};
}
/** One pass of algebraic simplification, using nested record patterns. */
Expr simplify(Expr e) {
return switch (e) {
case Add(Num(int a), Num(int b)) -> new Num(a + b);
case Mul(Num(int a), Num(int b)) -> new Num(a * b);
case Add(Expr l, Num(int z)) when z == 0 -> simplify(l);
case Mul(Expr l, Num(int one)) when one == 1 -> simplify(l);
case Mul(Num(int zero), Expr _) when zero == 0 -> new Num(0);
case Add(Expr l, Expr r) -> new Add(simplify(l), simplify(r));
case Mul(Expr l, Expr r) -> new Mul(simplify(l), simplify(r));
case Num n -> n;
case Var v -> v;
};
}
String show(Expr e) {
return switch (e) {
case Num(int v) -> Integer.toString(v);
case Var(String name) -> name;
case Add(Expr l, Expr r) -> "(" + show(l) + " + " + show(r) + ")";
case Mul(Expr l, Expr r) -> show(l) + " * " + show(r);
};
}
void main() {
// (x * 1 + 0) + 2 * 3
Expr e = new Add(new Add(new Mul(new Var("x"), new Num(1)), new Num(0)), new Mul(new Num(2), new Num(3)));
IO.println(show(e));
IO.println(show(simplify(e)));
IO.println("at x = 4: " + eval(e, 4) + " and " + eval(simplify(e), 4));
IO.println(simplify(new Mul(new Num(0), new Var("y"))));
}((x * 1 + 0) + 2 * 3)
(x + 6)
at x = 4: 10 and 10
Num[value=0]Add(Num(int a), Num(int b)) matches only an addition whose both sides are numbers, and binds the numbers inside. Rules such as "anything plus zero is that thing" and "zero times anything is zero" read almost exactly like their mathematical statements. Compilers, query planners and rule engines are full of code like this, which is one reason those programs were early adopters of pattern matching in other languages.
The records, interface and methods sit at the top level of a compact source file, so they are all members of the implicit class. In a real project Expr and its records would live in their own files, or nested together in one file as Expr.Num, Expr.Add and so on.
Two ways to add behaviour
You now have two designs for "different kinds of thing":
- Polymorphism: put an abstract method on the interface and implement it in each class, as with
Farein Interfaces, inheritance and generics. - Data-oriented: make the interface sealed, make the kinds records, and write each operation as a switch.
Neither is always better; they trade off along what is known as the expression problem. With polymorphism, adding a new kind is easy (one new class, nothing else changes) and adding a new operation is hard (edit every class). With sealed types and switches it is the reverse: a new operation is one new function, while a new kind means visiting every switch, and the compiler tells you exactly which.
Rules of thumb that experienced Java developers use:
- If outside code (plugins, other teams, library users) must be able to add new kinds, use an ordinary interface and polymorphism. A sealed type is a closed world.
- If the set of kinds is part of your domain and changes rarely (payment methods, shapes of a message, nodes of a syntax tree, results of an operation such as
SuccessorFailure), and the operations multiply, use sealed types and pattern matching. - Keep behaviour that is intrinsic to a kind (a
Locationchecking its own latitude) on the record itself, and put cross-cutting questions (fees, reports, serialisation) in switches.
One more JDK 25 note. Patterns over primitive types, such as case int i when i > 10, are still a preview feature in JDK 25 (JEP 507): without --enable-preview the compiler says "primitive patterns are a preview feature and are disabled by default". Everything else in this lesson is final and safe for production.
Common misconceptions
Misconception
"Records are just a shortcut for JavaBeans." Accessors are name(), not getName(); there are no setters; the class is final and its state is exactly its components. Records model values. Some older frameworks expected bean conventions, though most current ones understand records.
Misconception
"A record is deeply immutable." Its fields are final, but if a component is a mutable object (an ArrayList, an array), its contents can still change. Copy such components in the compact constructor.
Misconception
"Adding default to a switch over a sealed type makes it safer." It makes it quieter. A new subtype will flow into default without any error, which is usually exactly the bug exhaustiveness checking would have caught.
Misconception
"Pattern matching is just a nicer instanceof and cast." For a single type test, roughly yes. With record patterns, nesting, guards and exhaustiveness, it becomes a way of writing whole algorithms over structured data, checked by the compiler.
Exercises
1. Records, sealed types and pattern matching
Warm-upComputationalWhat does this program print?
record Point(int x, int y) {}
void main() {
IO.println(new Point(3, -1));
}
2. Records, sealed types and pattern matching
Warm-upComputationalWhat does this program print?
record Tag(String name) {}
void main() {
var a = new Tag("java");
var b = new Tag("java");
IO.println((a == b) + " " + a.equals(b));
}
3. Records, sealed types and pattern matching
CoreComputationalUsing the Expr hierarchy and eval from the lesson, what does this print?
IO.println(eval(new Mul(new Add(new Var("x"), new Num(2)), new Var("x")), 5));
4. Records, sealed types and pattern matching
CoreComputationalWhat does this program print?
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
String size(Shape s) {
return switch (s) {
case Circle c when c.r() > 10 -> "large circle";
case Circle c -> "circle";
case Square(double side) when side > 10 -> "large square";
case Square _ -> "square";
};
}
void main() {
IO.println(size(new Square(12)) + ", " + size(new Circle(3)));
}
5. Records, sealed types and pattern matching
CoreHumanPayment is sealed and permits Card, MobileMoney and BankTransfer. Several switches over it have no default. A developer adds record Voucher(String code, long cents) implements Payment {} and adds Voucher to the permits list. What happens?
6. Records, sealed types and pattern matching
StretchHumanWhich of these are allowed in a record declaration? Choose all that apply.
7. Records, sealed types and pattern matching
StretchHumanIn a switch over Payment, a developer writes case Card(_, long cents) -> cents / 100; and then case Card(int n, long cents) when n == 2 -> cents / 200;. What does javac do?
Further reading and resources
- JEP 395: RecordsRecords, final in JDK 16, with the design rationale.
- JEP 409: Sealed ClassesSealed classes and interfaces, final in JDK 17.
- JEP 441: Pattern Matching for switchType patterns, guards and exhaustiveness in switch, final in JDK 21.
- JEP 440: Record PatternsDeconstructing records in patterns, final in JDK 21.
- JEP 456: Unnamed Variables & PatternsThe underscore for components you do not need, final in JDK 22.
- JEP 507: Primitive Types in Patterns, instanceof, and switch (Third Preview)Still a preview feature in JDK 25.
- Project AmberThe OpenJDK project behind records, sealed types, patterns and other productivity features.