Skip to content

Commit fe6ea28

Browse files
committed
Drop statements after the first converted switch expression
Fixes #828
1 parent 5ba6187 commit fe6ea28

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import org.openrewrite.staticanalysis.kotlin.KotlinFileChecker;
3232

3333
import java.util.List;
34+
import java.util.concurrent.atomic.AtomicReference;
3435

3536
import static org.openrewrite.Tree.randomId;
3637

@@ -59,10 +60,15 @@ public TreeVisitor<?, ExecutionContext> getVisitor() {
5960
@Override
6061
public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
6162
J.Block b = super.visitBlock(block, ctx);
63+
AtomicReference<Boolean> newReturn = new AtomicReference<>(false);
6264
return b.withStatements(ListUtils.map(b.getStatements(), statement -> {
65+
if (newReturn.get()) {
66+
return null; // Drop statements after the first converted switch expression
67+
}
6368
if (statement instanceof J.Switch) {
6469
J.Switch sw = (J.Switch) statement;
6570
if (canConvertToSwitchExpression(sw)) {
71+
newReturn.set(true);
6672
J.SwitchExpression switchExpression = convertToSwitchExpression(sw);
6773
return new J.Return(randomId(), sw.getPrefix(), Markers.EMPTY, switchExpression);
6874
}

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,4 +330,41 @@ String doFormat(String str) {
330330
)
331331
);
332332
}
333+
334+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/828")
335+
@Test
336+
void removeUnreachableReturnAfterExhaustiveEnumSwitchWithMultipleValues() {
337+
rewriteRun(
338+
//language=java
339+
java(
340+
"""
341+
class Test {
342+
enum Color { RED, GREEN, BLUE }
343+
344+
public String getName(Color color) {
345+
switch (color) {
346+
case RED: return "Red";
347+
case GREEN: return "Green";
348+
case BLUE: return "Blue";
349+
}
350+
return "Unknown";
351+
}
352+
}
353+
""",
354+
"""
355+
class Test {
356+
enum Color { RED, GREEN, BLUE }
357+
358+
public String getName(Color color) {
359+
return switch (color) {
360+
case RED -> "Red";
361+
case GREEN -> "Green";
362+
case BLUE -> "Blue";
363+
};
364+
}
365+
}
366+
"""
367+
)
368+
);
369+
}
333370
}

0 commit comments

Comments
 (0)