Skip to content

Fix RemoveRedundantTypeCast removing cast that gives a var lambda its target type#925

Merged
timtebeek merged 1 commit into
mainfrom
tim/fix-924-lambda-var-cast
Jun 29, 2026
Merged

Fix RemoveRedundantTypeCast removing cast that gives a var lambda its target type#925
timtebeek merged 1 commit into
mainfrom
tim/fix-924-lambda-var-cast

Conversation

@timtebeek

@timtebeek timtebeek commented Jun 29, 2026

Copy link
Copy Markdown
Member

RemoveRedundantTypeCast already guards against removing a cast whose operand is a lambda or method reference, but the check only matched when the operand was the direct cast expression. When the lambda is wrapped in parentheses — var converter = (Function<Integer, String>) (i -> Integer.toString(i)); — the operand is a J.ControlParentheses/J.Parentheses node, so the guard missed it and removed the cast.

For a var local the cast is the only thing supplying the lambda's target type, so removing it produces code that does not compile (cannot infer type for local variable).

This unwraps parentheses before the lambda / method-reference check. The analogous method-reference form was already preserved (its operand isn't parenthesized); a regression test is added for it too.

… target type

The lambda/member-reference guard only matched when the cast operand was
the direct expression. When the operand is wrapped in parentheses (e.g.
`(Function<Integer, String>) (i -> ...)`), the operand is a
J.ControlParentheses/J.Parentheses, so the guard missed it and the cast
was removed. For a `var` local the cast is the sole source of the target
type, so removal breaks compilation.

Unwrap parentheses before checking for a lambda or method reference.

Fixes #924
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Jun 29, 2026
@timtebeek timtebeek merged commit 0fb105c into main Jun 29, 2026
1 check passed
@timtebeek timtebeek deleted the tim/fix-924-lambda-var-cast branch June 29, 2026 11:56
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Jun 29, 2026
@protocol7

Copy link
Copy Markdown
Contributor

Thanks!

@timtebeek

Copy link
Copy Markdown
Member Author

Thank you for the report!

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

Development

Successfully merging this pull request may close these issues.

RemoveRedundantTypeCast removes the cast that gives a lambda its target type when assigned to var

2 participants