Skip to content

Skip var when target type inference widens a generic argument#1103

Merged
timtebeek merged 1 commit into
mainfrom
tim/fix-javasourcefile-list-type
May 16, 2026
Merged

Skip var when target type inference widens a generic argument#1103
timtebeek merged 1 commit into
mainfrom
tim/fix-javasourcefile-list-type

Conversation

@timtebeek
Copy link
Copy Markdown
Member

Summary

List<I> x = singletonList(c) where c is a C extends I keeps the LST type as List<I> via target type inference, but converting to var x = List.of(c) makes javac re-infer List<C> — breaking any downstream usage that requires the declared supertype.

UseVarForGenericMethodInvocations now detects this by checking each argument against its resolved parameter type: when the parameter is a bare (non-parameterized) class that is a strict supertype of the argument, target inference widened a <T> substitution and the conversion is skipped.

Test plan

  • New test declaredSupertypeWidensTypeArgument in UseVarForGenericMethodInvocationsTest
  • All existing tests in org.openrewrite.java.migrate.lang.var.* pass

`List<I> x = singletonList(c)` where `c` is a `C extends I` keeps the
LST type as `List<I>` via target type inference. Converting to
`var x = List.of(c)` drops the target context, so javac re-infers
`List<C>` and downstream usages expecting `List<I>` fail to compile.

Detect the widening by comparing each argument's type to its resolved
parameter type: when the parameter is a bare class (not parameterized)
that is a strict supertype of the argument, target inference widened
a `<T>` substitution, and switching to `var` would narrow it back.
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite May 16, 2026
@timtebeek timtebeek merged commit 568b7a9 into main May 16, 2026
1 check passed
@timtebeek timtebeek deleted the tim/fix-javasourcefile-list-type branch May 16, 2026 11:34
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite May 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant