When using pattern matching on records, matching is done against the canonical constructor of the record. This implies listing all the components
in the canonical constructor even if some are unused. To make the intent of not using the component clear, Java 22 introduced the unnamed variable
pattern _.
Because we can only pattern match against the canonical constructor, there is no need to disambiguate by specifying the types of its parameters. Therefore, the type of unused variables in pattern matching should be omitted, as it does not bring additional value.
Remove the type of the unused component.
record Guest(String name, String email, String phoneNumber) {}
String greet(Object o) {
if (o instanceof Guest(String name, String _, String _)) { // Noncompliant
return "Hello " + name + "!";
}
return "Hello!";
}
String switchToGreet(Object o) {
return switch (o) {
case Guest(String name, String _, String _) -> "Hello " + name + "!"; // Noncompliant
default -> "Hello!";
};
}
record Guest(String name, String email, String phoneNumber) {}
String greet(Object o) {
if (o instanceof Guest(String name, _, _)) {
return "Hello " + name + "!";
}
return "Hello!";
}
String switchToGreet(Object o) {
return switch (o) {
case Guest(String name, _, _) -> "Hello " + name + "!";
default -> "Hello!";
};
}