Sub topic 6
Refresher: type patterns and record patterns
This chapter assumes you know Java syntax, records, instanceof, and switch. It reviews two Java 21 features that the rest of this tutorial builds on: type patterns and record patterns. Every example here binds a name for every value it matches. That requirement is what unnamed patterns relax later.
Type patterns
A type pattern combines a type test with a variable declaration. If the test succeeds, Java casts the value and assigns it to the new variable, called a pattern variable.
class TypePatterns {
static int length(Object o) {
if (o instanceof String s) {
return s.length();
}
return -1;
}
public static void main(String[] args) {
System.out.println(length("hello")); // 5
System.out.println(length(42)); // -1
}
}The variable s is in scope only where the compiler can prove the match succeeded. Inside the if body it is a String. Outside, it does not exist.
The same pattern works as a case label in a switch:
class Labels {
static String label(Object o) {
return switch (o) {
case String s -> "text of length " + s.length();
case Integer i -> "number " + i;
default -> "something else";
};
}
public static void main(String[] args) {
System.out.println(label("abc")); // text of length 3
System.out.println(label(7)); // number 7
System.out.println(label(2.5)); // something else
}
}A switch over patterns must cover every possible input. Here the default branch does that.
Record patterns
A record pattern matches a record and takes it apart in the same step. You write the record's name and then one nested pattern for each component, in declaration order.
record Point(int x, int y) {}
class PointDemo {
static String show(Object o) {
if (o instanceof Point(int x, int y)) {
return "x=" + x + ", y=" + y;
}
return "not a point";
}
public static void main(String[] args) {
System.out.println(show(new Point(3, 4))); // x=3, y=4
System.out.println(show("hi")); // not a point
}
}This replaces a type test followed by calls to p.x() and p.y(). The match succeeds only if o is a Point. Then Java reads each component and tests it against its nested pattern. Here the nested patterns are int x and int y, which always match.
Nested record patterns
Nested patterns can themselves be record patterns, so one expression can reach into several layers.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
class LineDemo {
static int lengthSquared(Object o) {
if (o instanceof Line(Point(int x1, int y1), Point(int x2, int y2))) {
int dx = x2 - x1;
int dy = y2 - y1;
return dx * dx + dy * dy;
}
return -1;
}
public static void main(String[] args) {
System.out.println(lengthSquared(new Line(new Point(0, 0), new Point(3, 4)))); // 25
}
}The compiler treats a component whose declared type already equals the pattern's type as always matching. Nested Point patterns on Point components therefore never fail on type grounds. Only a null component can make them fail, because a record pattern does not match null.
Record patterns in a switch
Record patterns work well with sealed types. Because the compiler knows every permitted subtype, it can check that the switch is exhaustive without a default branch.
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
class Area {
static double area(Shape s) {
return switch (s) {
case Circle(double r) -> Math.PI * r * r;
case Rectangle(double w, double h) -> w * h;
};
}
public static void main(String[] args) {
System.out.println(area(new Rectangle(2, 3))); // 6.0
}
}If you later add a third permitted record, this switch stops compiling until you handle it. That check is the main reason to prefer sealed types with pattern matching.
Common errors
- Using a pattern variable out of scope. A variable bound in
if (o instanceof String s)is not available after theifunless the compiler can prove the match succeeded, for example after anif (!(o instanceof String s)) return;. - Wrong component count. A record pattern must list one pattern for every component.
Point(int x)does not compile. - Expecting
nullto match. A record pattern never matchesnull, so anullrecord value falls through to the next case or branch. - Incompatible types.
o instanceof Point(String a, String b)fails to compile because the components areint.
What is awkward so far
Look again at Line(Point(int x1, int y1), Point(int x2, int y2)). To read only the start point's x, you would still have to invent names for y1, x2, and y2, and none of them would be used. In case Circle c and case Rectangle r, a name can be required even when the branch ignores it. The next chapters remove that requirement.
Exercise
Given record Point(int x, int y) {}, why does if (o instanceof Point(int x)) { ... } fail to compile, and what is the smallest change that makes it compile?
Show answer
A record pattern must have one nested pattern for each record component, in order, and Point has two components. Adding the second one, as in o instanceof Point(int x, int y), makes it compile. At this stage you have to name y even if you never use it.
Exercise
Given record Box(Object content) {}, what does new Box(null) instanceof Box(String s) evaluate to, and why?
Show answer
It evaluates to false. The type pattern String s nested inside a record pattern needs a non-null value of type String. A null component cannot match it, so the whole pattern fails without an exception.