diff --git a/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java b/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java index 14ae3dd37fc..0785489c645 100644 --- a/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java +++ b/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java @@ -79,6 +79,11 @@ public static boolean isAtLeast21() { return FEATURE >= 21; } + /** Returns true if the current runtime is JDK 22 or newer. */ + public static boolean isAtLeast22() { + return FEATURE >= 22; + } + /** * Returns the latest {@code --release} version. * diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java index 71e12a7f237..0e8f41a500e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java @@ -198,6 +198,7 @@ public final class UnusedVariable extends BugChecker implements CompilationUnitT this.exemptNames = ImmutableSet.builder() .add("ignored") + .add("") // `var _ = ...` is handled as an empty variable name .addAll(flags.getListOrEmpty("Unused:exemptNames")) .build(); diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java index 92107250de7..4db2f04b54f 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java @@ -1679,4 +1679,19 @@ public void parameterUsedInOverride() { .expectUnchanged() .doTest(); } + + @Test + public void underscoreVariable() { + assumeTrue(RuntimeVersion.isAtLeast22()); + refactoringHelper + .addInputLines( + "Test.java", + "class Test {", + " public static void main(String[] args) {", + " var _ = new Object();", + " }", + "}") + .expectUnchanged() + .doTest(); + } }