Use unnamed variable for unused try-with-resources resource on Java 21+#930
Merged
Merged
Conversation
UseTryWithResources always emitted a named resource variable, even when the resource is never referenced in the try body. Under -Xlint:all -Werror that unused variable fails the build. When the resource is unused in the try body and the target Java version is >= 21, emit the unnamed variable _ (JEP 443/456) instead. Fixes #927
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
UseTryWithResourcesnames the resource variable even when it is not referenced in the try body, producing an unused-variable warning that fails-Werrorbuilds #927UseTryWithResourcesalways emitted a named resource variable when convertingtry/finallyto try-with-resources, even when the resource is never referenced inside the try body. On codebases compiled with-Xlint:all -Werror(which promotes theunusedwarning to an error), the rewritten code no longer compiles.Change
When the resource variable is not referenced anywhere in the try body and the target Java version is >= 21, the recipe now emits the unnamed variable
_(JEP 443 preview in Java 21, finalized as JEP 456 in Java 22) instead of a named variable:For targets below Java 21 (where
_is not available) the existing behavior is preserved — the named variable is kept. Resources that are read in the body keep their name on all versions.The renamed variable's
JavaType.Variableand identifierfieldTypeare updated alongside the printed name so type validation stays consistent.Tests
unusedResourceUsesUnnamedVariableOnJava21— unused resource becomes_on Java 21unusedResourceKeepsNameBelowJava21— unused resource keeps its name below Java 21resourceUsedInBodyKeepsNameOnJava21— resource read in the body keeps its name on Java 21