Sub topic 7
Unnamed pattern variables: Type _
This chapter covers the Type _ form of a pattern: a type test that does not give the matched value a name. It assumes you know records, instanceof with type patterns, switch with case labels, and sealed interfaces. It also assumes you have seen unnamed local variables (var _) in earlier chapters. You need Java 22 or later to compile the code here.
The problem: a binding that nobody reads
A type pattern such as Circle c does two things. It tests whether a value is a Circle, and it declares a variable c that holds the value when the test succeeds. Often only the test matters:
case Circle c -> "round";Here c is never read. The name is noise, and a reader has to scan the branch to confirm it really is unused. Linters and IDEs often flag it as an unused variable. Since Java 22, you can write the pattern as Circle _. This is an unnamed pattern variable: the type test still happens, but no variable is declared.
Where `Type _` can appear
An unnamed pattern variable can replace the name in any type pattern:
- in a
caselabel of aswitch, - in an
instanceofexpression, - nested inside a record pattern, at any depth.
The underscore declares nothing, so you cannot refer to it. Writing _ in an expression is a compile error, and a second _ in the same scope is fine because neither one is a name.
In a switch
public class Balls {
sealed interface Ball permits RedBall, BlueBall, GreenBall {}
record RedBall(int size) implements Ball {}
record BlueBall(int size) implements Ball {}
record GreenBall(int size) implements Ball {}
static String temperature(Ball b) {
return switch (b) {
case RedBall _ -> "warm";
case BlueBall _ -> "cool";
case GreenBall _ -> "cool";
};
}
public static void main(String[] args) {
System.out.println(temperature(new RedBall(3)));
System.out.println(temperature(new GreenBall(1)));
}
}This prints warm and then cool. The switch is still exhaustive. The compiler checks coverage of the sealed hierarchy exactly as it does with named bindings, so adding a fourth permitted type later produces a compile error here. That check is the main reason to prefer a sealed switch over an if chain, and Type _ keeps it.
In a record pattern
Record patterns deconstruct a record into its components. Each component position takes a nested pattern, and that nested pattern can be a type pattern with an unnamed variable.
public class Pairs {
record Pair(Object first, Object second) {}
static String check(Object o) {
if (o instanceof Pair(String _, Integer n)) {
return "string then int " + n;
}
if (o instanceof Pair(_, Integer n)) {
return "anything then int " + n;
}
return "no match";
}
public static void main(String[] args) {
System.out.println(check(new Pair("a", 1)));
System.out.println(check(new Pair(2.5, 3)));
System.out.println(check(new Pair("a", "b")));
}
}The output is:
string then int 1
anything then int 3
no matchThe first pattern, Pair(String _, Integer n), requires the first component to be a String but does not bind it. The second pattern uses _ alone in that position, so the first component can be anything. These two forms look similar but mean different things. The bare _ is the unnamed pattern, which the next chapter covers in detail. Type _ still performs a type test.
`Type _` versus the other forms
| Form | Tests the type? | Declares a variable? | Typical use |
|---|---|---|---|
| `Circle c` | Yes | Yes, `c` | You need the value |
| `Circle _` | Yes | No | Only the type matters |
| `_` (nested only) | No | No | The component is irrelevant |
The diagram shows how to choose between them for one record component.
When `Type _` matches null
Record patterns have a rule that affects how you should read Type _. A nested type pattern that is total for the component's declared type matches every value of that type, including null. A type pattern that is narrower than the component type does not match null, because null instanceof X is false.
public class NullComponents {
sealed interface Ball permits RedBall, BlueBall {}
record RedBall(int size) implements Ball {}
record BlueBall(int size) implements Ball {}
record Box(Ball content) {}
static String kind(Box b) {
return switch (b) {
case Box(RedBall _) -> "red";
case Box(Ball _) -> "other, possibly empty";
};
}
public static void main(String[] args) {
System.out.println(kind(new Box(new RedBall(2))));
System.out.println(kind(new Box(new BlueBall(2))));
System.out.println(kind(new Box(null)));
}
}This prints red, other, possibly empty, and other, possibly empty. RedBall _ rejects a null content. Ball _ is total for a component of type Ball, so it accepts the null. If you replaced the second case with Box(BlueBall _), the switch would still be exhaustive over non-null contents, but new Box(null) would match no case, and the switch would throw a MatchException at run time. The compiler cannot see this from the sealed hierarchy alone, so check which of your patterns are total when null components are possible.
Note that the switch selector b itself must not be null. Passing null as the Box throws a NullPointerException unless a case null label is present. That rule is unrelated to _.
Several patterns in one case
Normally a case label can have one pattern, because each pattern might bind a variable, and the body would not know which variable exists. If no pattern in the label declares a variable, that problem disappears. Unnamed pattern variables make this possible:
public class Warmth {
sealed interface Ball permits RedBall, BlueBall, GreenBall {}
record RedBall(int size) implements Ball {}
record BlueBall(int size) implements Ball {}
record GreenBall(int size) implements Ball {}
static String temperature(Ball b) {
return switch (b) {
case RedBall _ -> "warm";
case BlueBall _, GreenBall _ -> "cool";
};
}
public static void main(String[] args) {
System.out.println(temperature(new BlueBall(5)));
System.out.println(temperature(new RedBall(5)));
}
}The output is cool and then warm. The rules for a multi-pattern label are:
- Every pattern in the label must be free of named bindings.
case BlueBall _, GreenBall gis a compile error. - Record patterns are allowed if all their nested patterns are unnamed, for example
case Box(RedBall _), Box(BlueBall _). - Patterns in the same label must not dominate each other in a way the compiler rejects. For example,
case Ball _, RedBall _fails because the second pattern is unreachable. - The label still takes part in exhaustiveness checking, so covering all permitted subtypes across labels still satisfies the compiler.
A pattern with a named binding in one case and an unnamed variable in another case is fine, as the cases are independent.
Guards
A when guard applies to the whole label, so it also applies to every pattern in it. A guard can read other variables in scope, but it cannot read the unnamed ones.
static String check(Ball b, boolean strict) {
return switch (b) {
case RedBall _ when strict -> "strict red";
case RedBall _ -> "red";
default -> "other";
};
}Because a guard can use values from elsewhere, RedBall _ when strict can still be useful even though nothing about the ball is read. If you find yourself wanting size in the guard, you need a named variable or an accessor call on a named binding.
Common mistakes
- Using the name later. After
if (o instanceof Circle _), writing_.radius()does not compile. If the body needs the object, name it. - Assuming
Type _ignores the type. It does not.Pair(String _, Integer n)fails when the first component is not aString. Use bare_when the type is irrelevant. - Forgetting that a mixed label is illegal. One named binding in a multi-pattern label breaks the whole label.
- Overlooking null components. As shown above, a narrow type pattern rejects null, and a total one accepts it.
- Using
_on a Java version before 22. Java 21 treats_in this position as an error unless preview features are enabled, so check the compiler version when the build fails on a line that looks correct.
Choosing between a name and `_`
Use Type _ when the branch is a pure classification, such as mapping a type to a constant, a count, or a label. Keep a name when the body uses the value, or when the name documents intent in a way a comment would otherwise have to. A long record pattern with five unnamed variables and one named one can be harder to read than a plain accessor call. If most components are ignored, ask whether the pattern should match only the one component you need.
Exercise
Given record Pair(Object first, Object second) {}, what does o instanceof Pair(Integer _, _) test, and how does it differ from o instanceof Pair(_, _)?
Show answer
It is true when o is a Pair whose first component is an Integer. The second component is ignored entirely. Pair(_, _) is true for any non-null Pair, because neither position tests a type. In the first pattern, Integer _ is an unnamed pattern variable, so it still performs a type test, and a null first component fails it.
Exercise
Why does case BlueBall _, GreenBall g -> ... fail to compile, and how would you fix it if the body needs the green ball's size?
Show answer
A multi-pattern label may not declare any named binding, because the body could not know which variable was assigned. Split the label into two cases: case BlueBall _ -> ... and case GreenBall g -> ... g.size() .... The shared body must be duplicated or moved into a helper method.