RemoveRedundantTypeCast should not remove required downcast
Adds a failing test case for where RemoveRedundantTypeCast should not remove a downcast that is necessary for chained calls to get matching types.
Thanks for the runnable example!
This PR is stale because it has been open for 90 days with no activity. Remove stale label or comment or this will be closed in 7 days.
Summary
I successfully fixed the
dontRemoveNecessaryDowncasttest inRemoveRedundantTypeCastTest. The issue was that the recipe was incorrectly removing a type cast in a generic method call chain:
Optional.of((Bar) getBarImpl()).orElse(getBar())The cast
(Bar)is necessary here because:
- Without the cast,
Optional.of(getBarImpl())returnsOptional<BarImpl>- With the cast,
Optional.of((Bar) getBarImpl())returnsOptional<Bar>- The
orElse(getBar())method requiresOptional<Bar>sincegetBar()returnsBarThe fix adds a special case check in the
RemoveRedundantTypeCastrecipe that preserves type casts when:
- The cast is inside a method invocation
- The cast is widening a type (e.g., from
BarImpltoBar)- The method returns a parameterized (generic) type
This ensures that casts that affect generic type inference are preserved, preventing type compatibility issues in method chains.
Nice work!