Skip to main content
Open source

Use var for constructor call assignments

Recipe IDorg.openrewrite.java.migrate.lang.var.UseVarForConstructors
Artifactorg.openrewrite.recipe:rewrite-migrate-java

Replace explicit type declarations with var when the variable is initialized with a constructor call of exactly the same type. Does not transform when declared type differs from constructor type (e.g., interface vs implementation).

Single recipeJavaModerne Source Available License
Try in PlatformTry this recipe in the Moderne platform. Not a user yet? You’ll get a no-setup demo environment, with nothing to install or configure.

Examples

java
Before
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;

class Test<E, K, V> {
void test() {
// Basic constructor
StringBuilder sb = new StringBuilder();

// Constructor with arguments
StringBuilder sbWithArg = new StringBuilder("initial");

// Final modifier
final StringBuilder finalSb = new StringBuilder();

// Generics with concrete types
ArrayList<String> list = new ArrayList<>();

// Explicit type arguments on constructor (non-diamond)
ArrayList<String> explicitList = new ArrayList<String>();

// Nested generics with concrete types
HashMap<String, ArrayList<Integer>> map = new HashMap<>();

// Type variable in generic
ArrayList<E> typeVarList = new ArrayList<>();

// Multiple type variables
HashMap<K, V> typeVarMap = new HashMap<>();

// Nested type variables
HashMap<K, ArrayList<V>> nested = new HashMap<>();

// Inner class constructor
HashMap.SimpleEntry<String, Integer> entry = new HashMap.SimpleEntry<>("key", 1);

// In lambda
Runnable r = () -> {
ArrayList<String> lambdaList = new ArrayList<>();
};

// For-loop initializer
for (StringBuilder forSb = new StringBuilder(); forSb.length() < 10; forSb.append("x")) {
}

// Try-with-resources
try (ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0])) {
} catch (Exception e) {
}
}

// Instance initializer
{
StringBuilder initSb = new StringBuilder();
}

// Static initializer
static {
StringBuilder staticSb = new StringBuilder();
}
}
After
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;

class Test<E, K, V> {
void test() {
// Basic constructor
var sb = new StringBuilder();

// Constructor with arguments
var sbWithArg = new StringBuilder("initial");

// Final modifier
final var finalSb = new StringBuilder();

// Generics with concrete types
var list = new ArrayList<String>();

// Explicit type arguments on constructor (non-diamond)
var explicitList = new ArrayList<String>();

// Nested generics with concrete types
var map = new HashMap<String, ArrayList<Integer>>();

// Type variable in generic
var typeVarList = new ArrayList<E>();

// Multiple type variables
var typeVarMap = new HashMap<K, V>();

// Nested type variables
var nested = new HashMap<K, ArrayList<V>>();

// Inner class constructor
var entry = new HashMap.SimpleEntry<String, Integer>("key", 1);

// In lambda
Runnable r = () -> {
var lambdaList = new ArrayList<String>();
};

// For-loop initializer
for (var forSb = new StringBuilder(); forSb.length() < 10; forSb.append("x")) {
}

// Try-with-resources
try (var bais = new ByteArrayInputStream(new byte[0])) {
} catch (Exception e) {
}
}

// Instance initializer
{
var initSb = new StringBuilder();
}

// Static initializer
static {
var staticSb = new StringBuilder();
}
}

Usage

Run this recipe

This recipe has no required configuration options. Users of Moderne can run it via the Moderne CLI.

You will need to have configured the Moderne CLI on your machine before you can run the following command.

shell
mod run . --recipe UseVarForConstructors

If the recipe is not available locally, then you can install it using:

mod config recipes jar install org.openrewrite.recipe:rewrite-migrate-java:3.39.0

Data tables

Source files that had results
org.openrewrite.table.SourcesFileResults

Source files that were modified by the recipe run.

ColumnDescription
Source path before the runThe source path of the file before the run. null when a source file was created during the run.
Source path after the runA recipe may modify the source path. This is the path after the run. null when a source file was deleted during the run.
Parent of the recipe that made changesIn a hierarchical recipe, the parent of the recipe that made a change. Empty if this is the root of a hierarchy or if the recipe is not hierarchical at all.
Recipe that made changesThe specific recipe that made a change.
Estimated time savingAn estimated effort that a developer to fix manually instead of using this recipe, in unit of seconds.
CycleThe recipe cycle in which the change was made.
Source files that had search results
org.openrewrite.table.SearchResults

Search results that were found during the recipe run.

ColumnDescription
Source path of search result before the runThe source path of the file with the search result markers present.
Source path of search result after run the runA recipe may modify the source path. This is the path after the run. null when a source file was deleted during the run.
ResultThe trimmed printed tree of the LST element that the marker is attached to.
DescriptionThe content of the description of the marker.
Recipe that added the search markerThe specific recipe that added the Search marker.
Source files that errored on a recipe
org.openrewrite.table.SourcesFileErrors

The details of all errors produced by a recipe run.

ColumnDescription
Source pathThe file that failed to parse.
Recipe that made changesThe specific recipe that made a change.
Stack traceThe stack trace of the failure.
Recipe performance
org.openrewrite.table.RecipeRunStats

Statistics used in analyzing the performance of recipes.

ColumnDescription
The recipeThe recipe whose stats are being measured both individually and cumulatively.
Source file countThe number of source files the recipe ran over.
Source file changed countThe number of source files which were changed in the recipe run. Includes files created, deleted, and edited.
Cumulative scanning time (ns)The total time spent across the scanning phase of this recipe.
Max scanning time (ns)The max time scanning any one source file.
Cumulative edit time (ns)The total time spent across the editing phase of this recipe.
Max edit time (ns)The max time editing any one source file.