Skip to content
Advertisement

Automatically replacing with var using IntelliJ

I’m migrating some pre Java 10 code and I’m wondering if IntelliJ offers a way to automatically refactor the code to replace the variable declarations that uses the actual type with var wherever it’s possible.

The code is full of stuff like:

String status = "empty";
BigDecimal interest = BigDecimal.ZERO;
List<Future<Boolean>> results = es.invokeAll(tasks);
LocalDate start = LocalDate.of(2020, 1, 1);

And I would prefer:

var status = "empty";
var interest = BigDecimal.ZERO;
var results = es.invokeAll(tasks);
var start = LocalDate.of(2020, 1, 1);

I already looked in IntelliJ’s settings (Code Style/Inspections) and couldn’t find anything.

Advertisement

Answer

  1. Go to File | Settings, there select Editor | Inspections, then under Java | Java language level migration aids | Java 10.

  2. Right click on Local variable type can be omitted and select Weak Warning or similar.

  3. Move Your cursor onto any of those warnings in Your code (highlighted grey), open quick fix context help (alt+enter), at Replace explicit type with 'var' move to the right and select Fix all 'Local variable type can be omitted' problems in file

Thanks for @olga-klisho for the idea (in comments)

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement