Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(LambdaBlockToExpression): convert lambda with method invocation as well #241

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 @@ -46,12 +46,22 @@ public J.Lambda visitLambda(J.Lambda lambda, ExecutionContext ctx) {
J.Lambda l = super.visitLambda(lambda, ctx);
if (lambda.getBody() instanceof J.Block) {
List<Statement> statements = ((J.Block) lambda.getBody()).getStatements();
if (statements.size() == 1 && statements.get(0) instanceof J.Return) {
Space prefix = statements.get(0).getPrefix();
if (prefix.getComments().isEmpty()) {
return l.withBody(((J.Return) statements.get(0)).getExpression());
} else {
return l.withBody(((J.Return) statements.get(0)).getExpression().withPrefix(prefix));
if (statements.size() == 1) {
Statement statement = statements.get(0);
Space prefix = statement.getPrefix();
if (statement instanceof J.Return) {
Expression expression = ((J.Return) statement).getExpression();
if (prefix.getComments().isEmpty()) {
return l.withBody(expression);
} else {
return l.withBody(expression.withPrefix(prefix));
}
} else if (statement instanceof J.MethodInvocation) {
if (prefix.getComments().isEmpty()) {
return l.withBody(statement);
} else {
return l.withBody(statement.withPrefix(prefix));
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,35 @@ void doTest() {
);
}

@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/236")
@Test
void simplifyLambdaBlockReturningVoidAsWell2() {
//language=java
rewriteRun(
java(
"""
public class Main {

public void run() {
Runnable runHelloWorld = () -> {
System.out.println("Hello world!");
};
runHelloWorld.run();
}
}
""",
"""
public class Main {

public void run() {
Runnable runHelloWorld = () ->
System.out.println("Hello world!");
runHelloWorld.run();
}
}
"""
)
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -299,10 +299,9 @@ class Test {
void bar(Consumer<Integer> c) {
}
void foo() {
bar(i -> {
bar(i2 -> {
});
});
bar(i ->
bar(i2 -> {
}));
}
}
"""
Expand Down