Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 821
Fábio Avatar asked Dec 12 '25 22:12

Fábio


2 Answers

  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)

like image 139
slartidan Avatar answered Dec 14 '25 14:12

slartidan


I'm using IntelliJ IDEA 2021.3.2, but don't think the setting is new.

I've been struggling with this one myself.

It seems that the first time to install IntelliJ locally, by default, it will fall back to using traditional defining of variables (i.e. String s = new String();)

How I managed to change it into using var is after I declared something, for example new String(), either I pressed ⌥ Alt/Option+Enter to declare a variable for that declaration or by using ⌘ Command+⇧ Shift+V shortcut (I'm using Mac and classic Intellij key mapping, so YMMV) which activates declaration of a variable, this would show as follows:

change traditional declaration of variables with var

As you see, it suggest to hit that key combination shortcut or clicking on the settings button that would open a pop up like this one:

pop up from clicking the settings button

Make sure you have Declare var type selected and you should be good to go.

like image 38
Andrei Sfat Avatar answered Dec 14 '25 14:12

Andrei Sfat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!