Show contents
Chapter 2 of 7 · 20 min
Sealed types and pattern matching
By the end of this chapter, you'll be able to
- Declare a sealed interface and its implementations with sealed and permits
- Write an exhaustive switch with type patterns and record patterns
- Refine a case with a when guard and ignore a component with _
- Model a recursive structure with sealed records
A closed hierarchy
sealed restricts the classes that can implement an interface (or extend a class) to those listed after permits. Combined with records, it describes a "sum" type: a payment is either a card, or mobile money, or a transfer, and nothing else.
sealed interface Payment permits Card, MobileMoney, Transfer {}
record Card(String last4, double amount) implements Payment {}
record MobileMoney(String operator, String number, double amount) implements Payment {}
record Transfer(String iban, double amount, boolean international) implements Payment {}
double fee(Payment p) {
return switch (p) {
case Card c -> c.amount() * 0.015;
case MobileMoney(_, _, double a) when a < 10 -> 0.0;
case MobileMoney m -> m.amount() * 0.01;
case Transfer(_, _, boolean intl) -> intl ? 5.0 : 0.0;
};
}
String describe(Object o) {
return switch (o) {
case null -> "nothing";
case Integer i when i < 0 -> "negative integer";
case Integer i -> "integer " + i;
case String s -> "text of " + s.length() + " characters";
case Payment p -> "payment, fee " + fee(p);
default -> "other: " + o.getClass().getSimpleName();
};
}
void main() {
List<Payment> payments = List.of(
new Card("4242", 200.0), new MobileMoney("Orange Money", "+225 01", 8.0),
new MobileMoney("M-Pesa", "+254 07", 50.0), new Transfer("FR76…", 1000.0, true));
for (Payment p : payments) {
IO.println(p.getClass().getSimpleName() + ": " + fee(p));
}
IO.println(describe(-4) + " / " + describe("Lomé") + " / " + describe(null) + " / " + describe(3.5));
Object o = new Card("1234", 10);
if (o instanceof Card(var last, var amount) && amount > 5) {
IO.println("card ending in " + last);
}
}
Card: 3.0
MobileMoney: 0.0
MobileMoney: 0.5
Transfer: 5.0
negative integer / text of 4 characters / nothing / other: Double
card ending in 1234
case Card cis a type pattern: ifpis aCard, it's available under the namec, already cast.case MobileMoney(_, _, double a)is a record pattern: it deconstructs the record and names its components._(Java 22+) ignores the ones you don't need.when a < 10is a guard: the case only applies if the condition is true. Cases are tried in order, hence the guarded case placed before the general one.- The
switchinfeehas nodefault: the compiler knows the three cases cover every possibility, because the interface is sealed. OnObject, however,defaultis mandatory. case nullhandlesnullexplicitly; without it, aswitchthrows aNullPointerException.- Patterns also work with
instanceof:o instanceof Card(var last, var amount).
The general MobileMoney pattern applies: 50 × 0.01 = 0.5.
Text description of the animation
- We compute the fee for an M-Pesa payment of 50.
- First pattern: p isn't a Card, move on to the next one.
- The record pattern matches and extracts a = 50, but the guard a < 10 is false: carry on.
- The general MobileMoney pattern applies: 50 × 0.01 = 0.5.
Why it beats a chain of ifs
With a series of if (p instanceof Card) … else if …, forgetting a case compiles without complaint and the bug shows up in production. With an exhaustive switch on a sealed type, adding a new payment method breaks compilation at every place that has to handle it. This is the data-oriented programming approach: simple, immutable data (records), a closed hierarchy (sealed) and processing that deconstructs it (patterns).
Your turn
Worked exercise
Solved exercise: an expression calculator
Model arithmetic expressions with a sealed interface Expr and four records: Num(double value), Sum(Expr left, Expr right), Product(Expr left, Expr right) and Neg(Expr e). Write eval(Expr), which computes the value, and show(Expr), which produces the text, with parentheses around sums and without .0 for whole numbers. Test with (2 + 3) × -1.5.
Hint 1
case Sum(Expr l, Expr r) -> eval(l) + eval(r);.Hint 2
permits allows the implementations declared in the same file. To display a whole number: v == Math.floor(v), then (long) v.Show the solution and common mistakes
sealed interface Expr {}
record Num(double value) implements Expr {}
record Sum(Expr left, Expr right) implements Expr {}
record Product(Expr left, Expr right) implements Expr {}
record Neg(Expr e) implements Expr {}
double eval(Expr e) {
return switch (e) {
case Num(double v) -> v;
case Sum(Expr l, Expr r) -> eval(l) + eval(r);
case Product(Expr l, Expr r) -> eval(l) * eval(r);
case Neg(Expr x) -> -eval(x);
};
}
String show(Expr e) {
return switch (e) {
case Num(double v) -> v == Math.floor(v) ? String.valueOf((long) v) : String.valueOf(v);
case Sum(Expr l, Expr r) -> "(" + show(l) + " + " + show(r) + ")";
case Product(Expr l, Expr r) -> show(l) + " × " + show(r);
case Neg(Expr x) -> "-" + show(x);
};
}
void main() {
Expr e = new Product(new Sum(new Num(2), new Num(3)), new Neg(new Num(1.5)));
IO.println(show(e) + " = " + eval(e));
}
(2 + 3) × -1.5 = -7.5
This is how compilers and rule engines work: a tree of immutable data, and functions that walk it with patterns.
Common mistakes:
- Adding
defaulttoeval: the day you addDivision, the compiler no longer warns you. - Forgetting the parentheses around sums:
2 + 3 × -1.5would read as a different expression, worth -2.5.
Summary
- 1sealed … permits closes a hierarchy: the compiler knows every implementation.
- 2Type patterns and record patterns deconstruct a value directly in a case.
- 3when adds a condition to a case; _ ignores a component; cases are tried in order.
- 4A switch without default on a sealed type is exhaustive: a new type breaks compilation where it should.
- 5Records + sealed + patterns: data-oriented programming in Java.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.