From 28099ccaf0224bc42f5cb27660286647d9937baf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Merlin=20B=C3=B6gershausen?= Date: Thu, 12 Sep 2024 17:54:19 +0200 Subject: [PATCH] Don't use var on local array variables that are initialized by an array initializer (#552) --- .../migrate/lang/var/UseVarForObject.java | 3 ++- .../lang/var/UseVarForObjectsTest.java | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java b/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java index f91c98ce0b..f067c58d39 100644 --- a/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java +++ b/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java @@ -75,7 +75,8 @@ public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations v boolean isPrimitive = DeclarationCheck.isPrimitive(vd); boolean usesGenerics = DeclarationCheck.useGenerics(vd); boolean usesTernary = DeclarationCheck.initializedByTernary(vd); - if (isPrimitive || usesGenerics || usesTernary) { + boolean usesArrayInitializer = vd.getVariables().get(0).getInitializer() instanceof J.NewArray; + if (isPrimitive || usesGenerics || usesTernary || usesArrayInitializer) { return vd; } diff --git a/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForObjectsTest.java b/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForObjectsTest.java index c1e31ebd8d..852e42424f 100644 --- a/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForObjectsTest.java +++ b/src/test/java/org/openrewrite/java/migrate/lang/var/UseVarForObjectsTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.openrewrite.DocumentExample; +import org.openrewrite.Issue; import org.openrewrite.test.RecipeSpec; import static org.openrewrite.java.Assertions.*; @@ -59,6 +60,7 @@ void m() { ); } + @Test void reassignment() { //language=java @@ -310,6 +312,25 @@ void m() { @Nested class NotApplicable { + + @Test + @Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/551") + void arrayInitializer() { + //language=java + rewriteRun( + java( + """ + package com.example.app; + + class A { + void m() { + String[] dictionary = {"aa", "b", "aba", "ba"}; + } + } + """) + ); + } + @Test void fieldInAnonymousSubclass() { //language=java