Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,16 @@ public J visitTypeCast(J.TypeCast typeCast, ExecutionContext ctx) {
if ((targetType instanceof JavaType.Primitive || castType instanceof JavaType.Primitive) && castType != expressionType) {
return visitedTypeCast;
}
if (typeCast.getExpression() instanceof J.Lambda || typeCast.getExpression() instanceof J.MemberReference) {
J castExpression = typeCast.getExpression();
while (castExpression instanceof J.Parentheses || castExpression instanceof J.ControlParentheses) {
castExpression = castExpression instanceof J.Parentheses ?
((J.Parentheses<?>) castExpression).getTree() :
((J.ControlParentheses<?>) castExpression).getTree();
}
if (castExpression instanceof J.Lambda || castExpression instanceof J.MemberReference) {
// Not currently supported, this will be more accurate with dataflow analysis.
// The cast supplies the target type for the lambda or method reference; removing it
// can break compilation, e.g. when assigned to a `var` local.
return visitedTypeCast;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.java.Assertions.javaVersion;

@SuppressWarnings("ALL")
class RemoveRedundantTypeCastTest implements RewriteTest {
Expand Down Expand Up @@ -489,6 +490,50 @@ public MapDropdownChoice(Supplier<? extends Map<K, ? extends V>> choiceMap) {
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/924")
void keepCastForLambdaAssignedToVar() {
rewriteRun(
//language=java
java(
"""
import java.util.function.Function;

class Example {
void run() {
var converter = (Function<Integer, String>) (i -> Integer.toString(i));
}
}
""",
spec -> spec.markers(javaVersion(25))
)
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/924")
void keepCastForMethodReferenceAssignedToVar() {
rewriteRun(
//language=java
java(
"""
import java.util.function.Supplier;

class Example {
static String make() {
return "";
}

void run() {
var supplier = (Supplier<String>) Example::make;
}
}
""",
spec -> spec.markers(javaVersion(25))
)
);
}

@Test
void returnPrimitiveIntToWrapperLong() {
rewriteRun(
Expand Down
Loading