Sub topic 8
The unnamed pattern: ignoring a whole record component
This chapter assumes you know records, instanceof with type patterns, switch with patterns, and the basic rule that _ can name a variable you never read. You also need nested record patterns, such as Line(Point(int x, int y), Point end). The chapter uses Java 22 or later, where unnamed patterns are final (JEP 456).
The problem: patterns that force you to name everything
A record pattern must account for every component of the record. If you only care about one component, you still have to write something for the others.
record Point(int x, int y) {}
class Before {
static boolean onXAxis(Object o) {
if (o instanceof Point(int x, int y)) {
return y == 0; // x is bound but never read
}
return false;
}
}The compiler accepts this code. But x suggests that it matters, and a reader has to scan the body to learn that it does not. Linters report it as an unused variable.
The unnamed pattern, written _, solves this. It means "match whatever is in this position and bind nothing."
record Point(int x, int y) {}
class After {
static boolean onXAxis(Object o) {
return o instanceof Point(_, int y) && y == 0;
}
}Two things that look alike
Java 22 added two separate features that both use _ inside patterns. They have different syntax, different matching rules, and different places where they are allowed.
| Form | Name | What it does |
|---|---|---|
| `Type _` | Unnamed pattern variable | A type pattern that tests the type but declares no variable |
| `var _` | Unnamed pattern variable with inferred type | Matches the component's declared type and declares no variable |
| `_` | Unnamed pattern | Matches anything and declares nothing. It has no type |
The first two are type patterns whose binding is unnamed. The third is a pattern of its own.
You can think of _ as a shorthand for var _. Both are unconditional, which means they match every value the component can hold. The difference is stylistic: _ is shorter and states plainly that you ignore the value.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
class Equivalent {
static int a(Line l) {
if (l instanceof Line(Point(int x, _), _)) return x;
return -1;
}
static int b(Line l) {
if (l instanceof Line(Point(int x, var _), var _)) return x;
return -1;
}
}Both methods return the start point's x coordinate. They behave the same.
What `_` matches
_ does not test anything. It does not check the type of the component, and it does not check for null. It accepts every value the component can hold, including null.
This matters when you compare it with a nested type pattern. Take a record with a component of type Object:
public class NullDemo {
record Box(Object content) {}
static String test(Box b) {
return switch (b) {
case Box(String _) -> "string content";
case Box(_) -> "anything else, including null";
};
}
public static void main(String[] args) {
System.out.println(test(new Box("hi")));
System.out.println(test(new Box(42)));
System.out.println(test(new Box(null)));
}
}Running this prints:
string content
anything else, including null
anything else, including nullThe first case, Box(String _), performs a type test. A null content is not a String, so it falls through. The second case, Box(_), performs no test, so it accepts the null content. That second case also makes the switch exhaustive over Box.
Compare this with Box(Object _). Here the pattern's type is the same as the component's declared type, so the pattern is unconditional and also matches null. When the declared component type is String, Box(String _) behaves the same way. The type pattern only rejects null when it has to perform a real type test, as in the example above.
A worked example with a sealed hierarchy
Unnamed patterns work well in switch over a sealed interface where each case reads one or two components.
public class Events {
sealed interface Event permits Click, KeyPress, Scroll {}
record Click(int x, int y) implements Event {}
record KeyPress(char key, boolean shift) implements Event {}
record Scroll(int dx, int dy) implements Event {}
static String summarize(Event e) {
return switch (e) {
case Click(int x, _) -> "click in column " + x;
case KeyPress(char k, _) -> "key " + k;
case Scroll(_, int dy) -> "vertical scroll by " + dy;
};
}
public static void main(String[] args) {
System.out.println(summarize(new Click(10, 20)));
System.out.println(summarize(new KeyPress('a', true)));
System.out.println(summarize(new Scroll(0, -3)));
}
}The output is:
click in column 10
key a
vertical scroll by -3Each case reads exactly the components it needs. The switch is still exhaustive, because every Event subtype is covered and each record pattern matches all instances of its record.
Ignoring a whole nested record
_ can stand in for a nested record as well as a primitive. You do not have to write out the structure of a record you ignore.
public class Nested {
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static int endY(Object o) {
if (o instanceof Line(_, Point(_, int y))) {
return y;
}
return -1;
}
public static void main(String[] args) {
System.out.println(endY(new Line(new Point(1, 2), new Point(3, 4))));
System.out.println(endY("not a line"));
}
}This prints 4 and then -1. The first _ skips the whole start point. The second _ skips the x of the end point.
There is one consequence of using _ for a nested record. Because _ matches anything, a null start point still matches. If you wrote Point(_, _) in that position instead, a null start would not match, because a record pattern never matches null. So _ and Point(_, _) are different patterns even though both ignore every value in the point.
Generic records
For a generic record, _ and var _ do not need to know the type arguments.
public class Pairs {
record Pair<A, B>(A first, B second) {}
static <A, B> A firstOf(Object o, Class<A> type) {
if (o instanceof Pair<?, ?>(var a, _) && type.isInstance(a)) {
return type.cast(a);
}
return null;
}
public static void main(String[] args) {
System.out.println(firstOf(new Pair<>("left", 7), String.class));
System.out.println(firstOf(new Pair<>(1, 2), String.class));
}
}The output is left and then null. The method reads the first component with var a and ignores the second with _, so it never has to name the type of second.
Combining it with a guard
An unnamed pattern composes with when guards, as long as the guard refers only to variables that exist.
public class Guards {
record Reading(String sensor, double value, long timestamp) {}
static String classify(Reading r) {
return switch (r) {
case Reading(_, double v, _) when v < 0 -> "negative";
case Reading(_, double v, _) when v > 100 -> "too high";
case Reading(String s, _, _) -> "ok from " + s;
};
}
public static void main(String[] args) {
System.out.println(classify(new Reading("a", -1.5, 0L)));
System.out.println(classify(new Reading("b", 250.0, 0L)));
System.out.println(classify(new Reading("c", 20.0, 0L)));
}
}This prints negative, too high, and ok from c. The last case is unconditional for Reading, so it makes the switch exhaustive.
Where `_` is not allowed
The unnamed pattern can appear only as a component of a record pattern. These uses are compile-time errors:
class Errors {
record Point(int x, int y) {}
static void bad(Object o) {
// if (o instanceof _) {} // error: _ is not a top-level pattern
// switch (o) { case _ -> {} } // error: same reason
// int n = _ + 1; // error: _ is not an expression
// if (o instanceof Point(int x, _) && x > _) {} // error: cannot read _
}
}The reasons follow from what the feature is for:
- A top-level
_would match every value, so it would be adefaultcase in disguise. Usedefaultfor that. _has no name, so it cannot be read._cannot name a field or a method parameter. That restriction belongs to unnamed variables in general and is covered in the chapter on where_is not allowed.
The top-level form that is allowed is an unnamed pattern variable, such as o instanceof Point _ or case Circle _ ->. That one is a type pattern with a type to test.
Choosing between `_`, `var _`, and `Type _`
Use this decision flow for each component of a record pattern.
Some practical rules follow from the flow:
- If the component's declared type is already the one you want, use
_. Writingint _orPoint _adds noise. - If you narrow a supertype component and care about the narrowing, use
Type _. For example,Box(String _)means "a box holding a string." - Use
var _rarely. It exists mainly for consistency withvar x, and_says the same thing.
Common errors
- Expecting
_to rejectnull. It does not. If a null component must not match, use a type pattern that performs a real type test, or check explicitly. - Writing the wrong number of components. A record pattern must have one entry per component.
Point(_)is an error for a two-component record, and you needPoint(_, _). If you ignore every component,Point(_, _)still tests that the value is a non-nullPoint. - Sharing a
casethat has bindings. Acasewith several patterns is allowed only if none of the patterns declares a named variable.case Click(int x, _), Scroll(int dx, _) ->fails.case Click(_, _), Scroll(_, _) ->compiles. - Compiling with an older release. On Java 21 the feature was a preview and needs
--enable-preview --release 21. On Java 20 and earlier,_is an error as an identifier. Java 22 is the first release where this works without flags.
Exercises
Exercise
Given record Pair(Object left, Object right) {}, which of these case labels matches new Pair(null, 5): case Pair(String _, _), case Pair(_, Integer _), or case Pair(_, _)?
Show answer
case Pair(_, Integer _) and case Pair(_, _) match. The first _ accepts null, and 5 is an Integer. case Pair(String _, _) does not match, because String _ is a type test on an Object component, and null is not a String.
Exercise
Why does if (o instanceof _) { ... } not compile, and which two forms could you write instead depending on what you need?
Show answer
_ is allowed only as a component inside a record pattern. At the top level it would match everything and do nothing, so the compiler rejects it. If you need a type test with no variable, write o instanceof Point _. In a switch, use default to match everything else.
Exercise
Rewrite this method so that it declares no unused variable: static int height(Object o) { if (o instanceof Rect(int w, int h)) return h; return 0; }
Show answer
static int height(Object o) { if (o instanceof Rect(_, int h)) return h; return 0; } The width component w was never read, so _ replaces int w.