Skip to content

Commit 5756db2

Browse files
committed
Keep parentheses when renaming typed lambda parameter to underscore
A single explicitly typed lambda parameter like `(RequestContext rc) -> ...` must remain parenthesized after renaming to `_`, otherwise the resulting `RequestContext _ -> ...` is invalid Java. Fixes #1080
1 parent 88ef91c commit 5756db2

2 files changed

Lines changed: 50 additions & 2 deletions

File tree

src/main/java/org/openrewrite/java/migrate/lang/ReplaceUnusedVariablesWithUnderscore.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,16 +78,21 @@ public J.Try.Catch visitCatch(J.Try.Catch _catch, ExecutionContext ctx) {
7878
public J.Lambda visitLambda(J.Lambda lambda, ExecutionContext ctx) {
7979
J.Lambda l = super.visitLambda(lambda, ctx);
8080
boolean willRename = false;
81+
boolean hasTypedParameter = false;
8182
for (J param : l.getParameters().getParameters()) {
8283
if (param instanceof J.VariableDeclarations) {
83-
for (J.VariableDeclarations.NamedVariable namedVariable : ((J.VariableDeclarations) param).getVariables()) {
84+
J.VariableDeclarations vd = (J.VariableDeclarations) param;
85+
if (vd.getTypeExpression() != null) {
86+
hasTypedParameter = true;
87+
}
88+
for (J.VariableDeclarations.NamedVariable namedVariable : vd.getVariables()) {
8489
if (renameVariableIfUnusedInContext(namedVariable, l.getBody())) {
8590
willRename = true;
8691
}
8792
}
8893
}
8994
}
90-
if (willRename && l.getParameters().isParenthesized() &&
95+
if (willRename && !hasTypedParameter && l.getParameters().isParenthesized() &&
9196
l.getParameters().getParameters().size() == 1) {
9297
l = l.withParameters(l.getParameters().withParenthesized(false));
9398
}

src/test/java/org/openrewrite/java/migrate/lang/ReplaceUnusedVariablesWithUnderscoreTest.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,49 @@ void example() {
205205
);
206206
}
207207

208+
@Test
209+
void replaceUnusedTypedLambdaParameterKeepsParentheses() {
210+
rewriteRun(
211+
//language=java
212+
java(
213+
"""
214+
package com.helloworld;
215+
216+
public class Main {
217+
interface Handler {
218+
String handle(RequestContext context);
219+
}
220+
221+
static class RequestContext {}
222+
223+
Handler route() {
224+
return (RequestContext rc) -> {
225+
return "result";
226+
};
227+
}
228+
}
229+
""",
230+
"""
231+
package com.helloworld;
232+
233+
public class Main {
234+
interface Handler {
235+
String handle(RequestContext context);
236+
}
237+
238+
static class RequestContext {}
239+
240+
Handler route() {
241+
return (RequestContext _) -> {
242+
return "result";
243+
};
244+
}
245+
}
246+
"""
247+
)
248+
);
249+
}
250+
208251
@Test
209252
void doNotReplaceUsedLambdaParameter() {
210253
rewriteRun(

0 commit comments

Comments
 (0)