Sub topic 2
Ignoring Catch Parameters and Lambda Parameters
Assume you know local variables, exceptions, lambda expressions, records, and basic instanceof and switch patterns. Java 22 lets you write _ when code must declare a variable but never reads its value.
Ignoring Catch and Lambda Parameters
A catch parameter names the exception object. If the handler only needs to choose a fallback, the name adds no useful information:
class Parsing {
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException _) {
return fallback;
}
}
}A lambda parameter can also be unnamed. This is useful when an API passes an argument that the lambda does not need:
import java.util.HashMap;
import java.util.Map;
class Defaults {
static Map<String, Integer> values() {
Map<String, Integer> result = new HashMap<>();
result.computeIfAbsent("retries", _ -> 3);
return result;
}
}The underscore communicates intent: the argument exists because the method requires it, not because the code needs its value.
Type and Record Patterns
A type pattern tests an object and binds it to a variable:
if (value instanceof String text) {
System.out.println(text.length());
}A record pattern tests a record and extracts its components:
record Point(int x, int y) {}
if (value instanceof Point(int x, int y)) {
System.out.println(x + y);
}Unnamed Pattern Variables: `Type _`
Use Type _ when you need to test a type but do not need the matched object:
if (value instanceof String _) {
System.out.println("The value is text.");
}This is an unnamed pattern variable. The type remains important, but there is no usable variable name.
The Unnamed Pattern: `_`
Inside a record pattern, _ ignores a component completely. It does not bind that component to a variable:
record Point(int x, int y) {}
record Line(Point start, Point end) {}
class Geometry {
static int startX(Object value) {
if (value instanceof Line(Point(int x, _), _)) {
return x;
}
return -1;
}
}Here, the code keeps the starting point's x value. It ignores the starting point's y value and the entire ending point.
| Form | Meaning |
|---|---|
| `String _` | Match a `String`, but do not bind the object |
| `Point(int x, _)` | Extract `x` and ignore the second component |
Exercise
In value instanceof Line(Point(int x, _), _), which values are available after the match?
Show answer
Only the starting point's x component is available as the variable x.