|
| 1 | +== Why is this an issue? |
| 2 | + |
| 3 | +When using pattern matching on records, matching is done against the canonical constructor of the record. |
| 4 | +This implies listing all the components in the canonical constructor even if some are unused. |
| 5 | +To make the intent of not using the component clear, Java 22 introduced the unnamed variable pattern `_`. |
| 6 | + |
| 7 | +Because we can only pattern match against the canonical constructor, there is no need to disambiguate by specifying the types of its parameters. |
| 8 | +Therefore, the type of unused variables in pattern matching should be omitted, as it does not bring additional value. |
| 9 | + |
| 10 | +== How to fix it |
| 11 | +Remove the type of the unused component. |
| 12 | + |
| 13 | +=== Code examples |
| 14 | + |
| 15 | +==== Noncompliant code example |
| 16 | + |
| 17 | +[source,java,diff-id=1,diff-type=noncompliant] |
| 18 | +---- |
| 19 | +record Guest(String name, String email, String phoneNumber) {} |
| 20 | +
|
| 21 | +String greet(Object o) { |
| 22 | + if (o instanceof Guest(String name, String _, String _)) { // Noncompliant |
| 23 | + return "Hello " + name + "!"; |
| 24 | + } |
| 25 | + return "Hello!"; |
| 26 | +} |
| 27 | +
|
| 28 | +String switchToGreet(Object o) { |
| 29 | + return switch (o) { |
| 30 | + case Guest(String name, String _, String _) -> "Hello " + name + "!"; // Noncompliant |
| 31 | + default -> "Hello!"; |
| 32 | + }; |
| 33 | +} |
| 34 | +---- |
| 35 | + |
| 36 | +==== Compliant solution |
| 37 | + |
| 38 | +[source,java,diff-id=1,diff-type=compliant] |
| 39 | +---- |
| 40 | +record Guest(String name, String email, String phoneNumber) {} |
| 41 | +
|
| 42 | +String greet(Object o) { |
| 43 | + if (o instanceof Guest(String name, _, _)) { |
| 44 | + return "Hello " + name + "!"; |
| 45 | + } |
| 46 | + return "Hello!"; |
| 47 | +} |
| 48 | +
|
| 49 | +String switchToGreet(Object o) { |
| 50 | + return switch (o) { |
| 51 | + case Guest(String name, _, _) -> "Hello " + name + "!"; |
| 52 | + default -> "Hello!"; |
| 53 | + }; |
| 54 | +} |
| 55 | +---- |
| 56 | + |
| 57 | +== Resources |
| 58 | +=== Documentation |
| 59 | +* https://openjdk.org/jeps/456[JEP 456: Unnamed Variables & Patterns] |
0 commit comments