Lesson · Records, Sealed Types & Pattern Matching
Pattern matching: types, deconstruction, guards
17 min readPattern Matching
Patterns test a value and bind its parts in one step: instanceof for flow scoping, switch for sealed families with guards and null cases, and record deconstruction to unwrap nested data without a single cast.
The dance that disappeared
For two decades the check-then-cast dance was the way through a type test. Patterns fold both steps into one:
// the dance: if (shape instanceof Circle) { Circle c = (Circle) shape; return Math.PI * c.r() * c.r(); } // the pattern: return switch (shape) { case Circle c -> Math.PI * c.r() * c.r(); case Square s -> s.s() * s.s(); }; // no default: the sealed family makes this total
Predict: why is there no default? Because Shape is sealed (last lesson), so the compiler knows the full case list and verifies coverage. The pattern binds each variable exactly when the test succeeds, which makes the cast after the check impossible to get wrong. It no longer exists.
Type patterns and flow scoping
A type pattern (Circle c) tests the value and names it. The name's scope follows the flow of the code, wherever the compiler can prove the test passed:
- Inside the true branch:
if (o instanceof Circle c) { c.r(); }bindscfor the block. - After an early return:
if (!(o instanceof Circle c)) return 0;makescusable for the rest of the method, because reaching there proves the test. - Through short-circuit operators:
o instanceof Circle c && c.r() > 1bindscfor the right side of&&; after||the compiler is equally careful about what is proven. - Nowhere else: the binding does not exist before the test or in places the compiler cannot verify, which removes the old bug class of using a cast variable outside its safe zone.
Flow scoping is the compiler tracking what is proven. The variable appears exactly where the proof exists, so both over-scoping (use before test) and the classic stray cast are structurally impossible.
Switch: patterns, guards, null
Switch became a pattern-matching construct: each case tests shape, guards add conditions, and null gets an explicit case:
return switch (o) { case Integer i when i < 0 -> "negative"; // guard: pattern plus condition case Integer i -> "integer " + i; // first match wins, so order matters case null -> "null!"; // null is a case, not an NPE default -> "other"; };
- Cases are tested top to bottom; the first matching pattern runs, so specific cases precede general ones.
- A
whenguard adds a boolean condition to a pattern; a failed guard means the next case is tried. case nullhandles null explicitly: without it, a switch on a reference that is null throws, exactly as before.- Over a sealed family, a switch without default is checked for exhaustiveness; with
Object, the compiler demands coverage or a default. - A case that can never be selected is refused: verified message
this case label is dominated by a preceding case label.
Order carries meaning now. 'Shape before Circle' was harmless in the old switch; here it is a dominance error, because the later case could never be chosen. The compiler refuses dead patterns instead of letting them rot.
Pattern desk · test and bind in one step
pick a caseradiusOrZero(new Circle(3)) → 3.0 radiusOrZero("x") → 0.0
The binding survives the early return because reaching the line proves the test; no cast, no second variable, no scope accident.
Every output and the dominance error were produced by javac 21 and a real run; the message is verbatim.
Record deconstruction: taking data apart in place
A record pattern lists the components a case needs, and nested patterns go as deep as the data:
case Line(Point from, Point to) -> { int dx = to.x() - from.x(); int dy = to.y() - from.y(); yield Math.sqrt(dx * dx + dy * dy); }
Line(Point from, Point to)both matches a Line and binds its two points; no accessor chain in sight.- Nested patterns (
Point(int x, int y)) unwrap all the way to primitives when the case needs the numbers, not the objects. - Unused components will be skippable with unnamed patterns (
_), finalised in Java 22; this course pins its code to Java 21, where they are still preview. - Deconstruction works with any record, and with classes that opt into the same protocol; records are the natural fit.
Patterns are the mirror image of record construction. The record builds a value from components; the record pattern takes it apart into exactly those components, keeping the two sides of the API visibly matched.
The pattern playbook
Replacing casts with patterns, in order:
- Anywhere a cast follows an instanceof, rewrite as a type pattern; the check and the name become one line.
- Over a sealed family, write the switch without default and let the compiler verify coverage as the family grows.
- Add guards (
when) instead of nesting conditions inside case bodies; keep specific patterns above general ones. - Handle null with an explicit
case nullwhen it can arrive, or document why it cannot. - Prefer record deconstruction over accessor chains inside the case; match the shape you need, not the whole object.
Tests and bindings travel together; casts stop being necessary. Written this way, the compiler checks more and the reader parses less, which is the entire point of the feature family.
Patterns test and bind in one step
Type patterns replace the instanceof-cast dance with flow-scoped names, switch cases carry patterns, guards and explicit null handling, and record patterns deconstruct nested data in place. Over sealed families the compiler verifies totality, and dead patterns are refused with a dominance error.
Interview angles
What is flow scoping for pattern variables?+
The bound name exists exactly where the compiler can prove the test succeeded: the true branch, the code after an early return on the negated test, and the right side of short-circuit operators when the test is to their left.
The old bug class ('used the cast variable outside the checked block') becomes unrepresentable: there is no variable to use outside its zone. The proof travels with control flow, not with braces alone.
if (!(o instanceof Circle c)) return 0; return c.r(); // reached only when o was a Circle
Common misconception: That the binding is scoped to the surrounding block like a normal local. It is scoped to the *proof*: moving code across the boundary changes what compiles.
Follow-up: Why does the negated check with return enable use after the if?
How do guards work in switch patterns?+
A guard (case Integer i when i < 0) adds a condition to a pattern; the case runs only when both match, and a failed guard falls through to the next case.
Because matching is top to bottom, guard cases go above their unguarded variants. Guards do not count for exhaustiveness the way unconditional patterns do; a guarded case alone does not complete a family.
case Integer i when i < 0 -> "negative"; case Integer i -> "integer " + i; // reached when the guard failed
Common misconception: That guarded and unguarded cases of the same pattern are 'the same case'. They are ordered alternatives with distinct conditions.
Follow-up: What happens if only the guarded Integer case is present and the value is 5?
What does 'this case label is dominated by a preceding case label' mean?+
The case can never be selected because an earlier case already matches everything it would: the compiler refuses dead patterns instead of shipping them.
Order matters: a general pattern before a specific one hides it. Verified with case Shape x before case Circle c; swapping the order fixes it. The check keeps pattern switches semantically honest as families evolve.
case Shape x -> "any"; // matches everything case Circle c -> "circle"; // error: dominated, never selected
Common misconception: That case order is stylistic here as it was for constants. With patterns, order decides reachability, and the compiler enforces it.
Follow-up: How does the fix read after swapping the two cases?
How does null handling change with pattern switches?+
Null must be its own case: case null -> .... Without it, a pattern switch on a null reference throws NullPointerException, exactly like the old switch.
The explicit case option removes the historic inconsistency where switch threw but no branch could handle it. In sealed-family switches without default, case null is also how the method stays total when null is possible.
case null -> "null!"; default -> "other";
Common misconception: That any pattern would match null. Patterns match types; null matches nothing until you say so.
Follow-up: What is the alternative to case null in older code?
What do record patterns deconstruct?+
A record's components, matched and bound in one pattern: case Line(Point from, Point to) gives the case the parts directly, nested as deeply as the pattern spells out.
The syntax mirrors the canonical constructor, so construction and deconstruction read as inverses. Component binding can go all the way to primitives (Point(int x, int y)), skipping the intermediate objects entirely when the case needs only numbers.
case Line(Point(int x1, int y1), Point(int x2, int y2)) -> ...
Common misconception: That deconstruction needs reflection or is slow. It compiles to direct accessor calls; there is no lookup magic at runtime.
Follow-up: Which part of a deconstruction pattern can be left unnamed, and since when?