Skip to content

Use unnamed variable for unused try-with-resources resource on Java 21+#930

Merged
timtebeek merged 1 commit into
mainfrom
tim/issue-927-unnamed-resource-variable
Jun 30, 2026
Merged

Use unnamed variable for unused try-with-resources resource on Java 21+#930
timtebeek merged 1 commit into
mainfrom
tim/issue-927-unnamed-resource-variable

Conversation

@timtebeek

@timtebeek timtebeek commented Jun 30, 2026

Copy link
Copy Markdown
Member

UseTryWithResources always emitted a named resource variable when converting try/finally to try-with-resources, even when the resource is never referenced inside the try body. On codebases compiled with -Xlint:all -Werror (which promotes the unused warning 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:

// before
Scope scope = openScope();
try {
} finally {
    scope.close();
}

// after (Java 21+)
try (Scope _ = openScope()) {
}

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.Variable and identifier fieldType are updated alongside the printed name so type validation stays consistent.

Tests

  • unusedResourceUsesUnnamedVariableOnJava21 — unused resource becomes _ on Java 21
  • unusedResourceKeepsNameBelowJava21 — unused resource keeps its name below Java 21
  • resourceUsedInBodyKeepsNameOnJava21 — resource read in the body keeps its name on Java 21

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
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Jun 30, 2026
@timtebeek timtebeek merged commit 6ed9dfd into main Jun 30, 2026
1 check passed
@timtebeek timtebeek deleted the tim/issue-927-unnamed-resource-variable branch June 30, 2026 16:56
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Jun 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

1 participant