Sub topic 6
Refresher: Type Patterns and Record Patterns
What this chapter assumes
This chapter reviews the pattern matching features that the rest of the tutorial builds on. It assumes you can read Java 17 code and know these things:
- Records, including their automatically generated accessor methods.
instanceofand casts.- Basic
switchexpressions. - Sealed interfaces, at the level of "the compiler knows every permitted subtype".
Everything here is final in Java 21. Nothing in this chapter uses the underscore yet. Watch for the bindings that go unused. They are the problem the next chapters solve.
Type patterns with instanceof
A type pattern combines a type test with a variable declaration. The variable is called a pattern variable, or binding. Before Java 16 you wrote the test and the cast separately:
if (o instanceof String) {
String s = (String) o;
System.out.println(s.length());
}With a type pattern, the test, the cast, and the declaration become one expression:
public class TypePatterns {
static String describe(Object o) {
if (o instanceof String s && !s.isEmpty()) {
return "string of length " + s.length();
}
if (o instanceof Integer i) {
return "integer, next is " + (i + 1);
}
return "something else";
}
public static void main(String[] args) {
System.out.println(describe("hello"));
System.out.println(describe(41));
System.out.println(describe(2.5));
}
}Three details matter in practice:
instanceofnever matchesnull.null instanceof String sisfalse, so the binding is never in scope with a null value.- The binding exists only where the compiler can prove the match succeeded. In
o instanceof String s && !s.isEmpty(), the right operand of&&can usesbecause it runs only after a successful match. This is called flow scoping. - The scope follows the control flow, not the braces. If a negated test exits the method, the binding is in scope after the
if.
public class FlowScope {
static int lengthOrZero(Object o) {
if (!(o instanceof String s)) {
return 0;
}
return s.length(); // s is in scope: reaching here means the match succeeded
}
public static void main(String[] args) {
System.out.println(lengthOrZero("four"));
System.out.println(lengthOrZero(4));
}
}Type patterns in switch
From Java 21, case labels can be patterns. The selector can be any reference type, so a switch can test types as well as constants.
public class SwitchPatterns {
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square q -> q.side() * q.side();
case Triangle t -> 0.5 * t.base() * t.height();
};
}
public static void main(String[] args) {
System.out.println(area(new Square(3)));
System.out.println(area(new Triangle(4, 5)));
}
}The switch has no default. Because Shape is sealed, the compiler knows the three cases cover every possible value and accepts the switch as exhaustive. If you later add a fourth permitted type, this switch stops compiling until you handle it. That is the main reason to prefer sealed hierarchies with pattern switches.
Other rules to keep in mind:
- Order matters. A label that matches everything a later label would match is a compile error, because the later label is unreachable. Writing
case Shape sbeforecase Circle cis rejected. This is called dominance. Put specific cases first and general ones last. nullis rejected by default. A pattern switch throwsNullPointerExceptionfor anullselector unless it has acase nulllabel.- A guard adds a condition.
case Circle c when c.radius() > 10 -> ...matches only if the type matches and thewhenexpression is true. A guarded label does not count toward exhaustiveness, so you still need a case that covers the same type without a guard.
Record patterns
A type pattern gives you the whole object. For a record, you usually want its components. A record pattern tests the type and extracts the components in one step. It calls the record's accessor methods and matches each result against a nested pattern.
public class RecordPatterns {
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static double length(Object o) {
if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) {
return Math.hypot(x2 - x1, y2 - y1);
}
return -1;
}
public static void main(String[] args) {
System.out.println(length(new Line(new Point(0, 0), new Point(3, 4))));
System.out.println(length("not a line"));
}
}This one pattern replaces a cast and four accessor calls. It names four variables: x1, y1, x2, y2. Reading it from the outside in:
Line(...)tests thatois aLine.Point(var x1, var y1)matches thestartcomponent, which must be aPoint, and binds its two components.- The second
Point(...)does the same forend.
The same pattern works in a switch, where each case can deconstruct a different record:
public class AreaWithRecordPatterns {
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
case Triangle(double b, double h) -> 0.5 * b * h;
};
}
static String size(Shape s) {
return switch (s) {
case Circle(double r) when r > 10 -> "large circle";
case Circle(double r) -> "circle";
case Square(double side) -> "square";
case Triangle t -> "triangle";
};
}
public static void main(String[] args) {
System.out.println(area(new Circle(2)));
System.out.println(size(new Circle(20)));
System.out.println(size(new Triangle(1, 1)));
}
}Look at size. In the second case, r is declared but never read, and side is declared and never read in the third. The compiler requires a pattern for each component, so you must write something there. The unnamed variables and patterns in this tutorial remove that noise.
The diagram below shows how the compiler-generated test for a nested pattern proceeds. Any failed step means the whole pattern does not match, and no bindings are in scope.
Details that cause surprises
Component patterns must fit the component type
Each nested pattern must be applicable to the declared type of the component. For Point(int x, int y), a pattern of int x or var x works. A pattern such as String x on an int component is a compile error. In Java 21, a primitive component needs a primitive pattern of exactly the same type, or var.
`var` infers the component type
var x1 in a record pattern takes the component's declared type. It is not a type test. It cannot fail, and it matches even a null component. Use var when the exact type adds nothing. Write the explicit type when it helps the reader, as in Circle(double r).
Null components are treated differently from null values
This is the least obvious rule. A record pattern does not match null itself. A nested type pattern that is total for the component type, meaning it covers every possible value of that type, does match a null component.
public class NullComponents {
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static String check(Line line) {
return switch (line) {
case Line(Point(var x, var y), Point end) -> "start x=" + x;
case Line(Point start, Point end) -> "start is null";
};
}
public static void main(String[] args) {
System.out.println(check(new Line(new Point(1, 2), new Point(3, 4))));
System.out.println(check(new Line(null, new Point(3, 4))));
}
}The first case fails for a null start because Point(var x, var y) is a record pattern, and record patterns never match null. The second case succeeds because Point start is a type pattern that is total for Point, so it accepts null. The program prints start x=1 and then start is null. Notice that end is bound in both cases and never used.
Bindings are scoped to where the match succeeded
Pattern variables obey the same flow scoping as in instanceof. In a switch rule, a binding is in scope only in that rule's body and guard. Two rules may reuse the same name without conflict.
Exhaustiveness covers nested patterns
For sealed hierarchies, the compiler checks exhaustiveness through nested record patterns too. If a record has a component of a sealed type, a switch must cover every permitted subtype for that component, or use a total pattern.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| A general case before a specific one, such as `case Shape s` before `case Circle c` | Compile error: the label is dominated | Order cases from most specific to least specific |
| Switch over a sealed type that misses a subtype | Compile error: the switch is not exhaustive | Add the missing case, or a `default` if you accept that trade-off |
| Wrong number of components, such as `Point(var x)` | Compile error: pattern arity does not match the record | Write one pattern per record component |
| Using a binding outside its scope | Compile error: cannot find symbol | Restructure the condition, or use the negated `if` with an early exit |
| A `null` selector in a pattern switch | `NullPointerException` at run time | Add `case null`, or check before switching |
| A guarded case as the only one for a type | Compile error: the switch is not exhaustive | Add an unguarded case for the same type |
The cost of required names
The rules so far all require you to write a binding for every position in a pattern. You face the same requirement elsewhere in Java. A loop must declare a variable. A catch block must declare a parameter. A lambda must list its parameters. Often the value is not needed, and the unused name misleads readers and triggers lint warnings.
The next chapters introduce _ as a way to say "this position exists, and I don't care about its value". Before moving on, make sure you can explain the difference between a type pattern such as Circle c and a record pattern such as Circle(double r). The unnamed pattern variable replaces the name in the first form, and the unnamed pattern replaces a whole component pattern in the second.
Exercise
Given record Pair(Object first, Object second) {}, what does this method return for new Pair("a", null) and for new Pair(null, "a")? Explain why.
static String test(Pair p) {
if (p instanceof Pair(String a, Object b)) {
return "match " + a;
}
return "no match";
}
Show answer
It returns "match a" for the first call and "no match" for the second. In the first call, first is the string "a", so String a matches, and Object b is a total pattern that accepts the null second component. In the second call, first is null, and String a is a type pattern that is not total for Object, so it does not match null.
Exercise
Why does this switch fail to compile, and how do you fix it? sealed interface Vehicle permits Car, Bike {} record Car(int seats) implements Vehicle {} record Bike(boolean electric) implements Vehicle {} static String kind(Vehicle v) { return switch (v) { case Car c when c.seats() > 4 -> "big car"; case Bike b -> "bike"; }; }
Show answer
The only Car case has a when guard, and a guarded case does not count toward exhaustiveness, so a Car with four or fewer seats has no matching case. Add an unguarded case Car c -> "car"; after the guarded one. The guarded case must stay first, or the more general one would dominate it.
Exercise
Write a method static int sumX(Object o) that returns the sum of the x values of both endpoints if o is a Line of two Point records (with int x, int y components), and 0 otherwise. Use a single record pattern.
Show answer
record Point(int x, int y) {} record Line(Point start, Point end) {} static int sumX(Object o) { if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2))) { return x1 + x2; } return 0; } The variables y1 and y2 are bound but never used, which is exactly the situation unnamed patterns address in later chapters.