Skip to content

Commit 28099cc

Browse files
authored
Don't use var on local array variables that are initialized by an array initializer (#552)
1 parent 759dbd7 commit 28099cc

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations v
7575
boolean isPrimitive = DeclarationCheck.isPrimitive(vd);
7676
boolean usesGenerics = DeclarationCheck.useGenerics(vd);
7777
boolean usesTernary = DeclarationCheck.initializedByTernary(vd);
78-
if (isPrimitive || usesGenerics || usesTernary) {
78+
boolean usesArrayInitializer = vd.getVariables().get(0).getInitializer() instanceof J.NewArray;
79+
if (isPrimitive || usesGenerics || usesTernary || usesArrayInitializer) {
7980
return vd;
8081
}
8182

src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForObjectsTest.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import org.junit.jupiter.api.Nested;
2020
import org.junit.jupiter.api.Test;
2121
import org.openrewrite.DocumentExample;
22+
import org.openrewrite.Issue;
2223
import org.openrewrite.test.RecipeSpec;
2324

2425
import static org.openrewrite.java.Assertions.*;
@@ -59,6 +60,7 @@ void m() {
5960
);
6061
}
6162

63+
6264
@Test
6365
void reassignment() {
6466
//language=java
@@ -310,6 +312,25 @@ void m() {
310312

311313
@Nested
312314
class NotApplicable {
315+
316+
@Test
317+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/551")
318+
void arrayInitializer() {
319+
//language=java
320+
rewriteRun(
321+
java(
322+
"""
323+
package com.example.app;
324+
325+
class A {
326+
void m() {
327+
String[] dictionary = {"aa", "b", "aba", "ba"};
328+
}
329+
}
330+
""")
331+
);
332+
}
333+
313334
@Test
314335
void fieldInAnonymousSubclass() {
315336
//language=java

0 commit comments

Comments
 (0)