Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ: search and replace 'var' declarations with actual types

Question: Is there a way to replace all var declaration with actual types in IntelliJ IDEA?

Context: I implemented a large feature using vars but turns out all developers in the team are against using vars and I have to rework it back to actual types.

like image 887
Sasha Shpota Avatar asked Sep 10 '19 11:09

Sasha Shpota


People also ask

How to search for a variable in IntelliJ?

From the main menu, select Edit | Find | Find in Files Ctrl+Shift+F . In the search field, type your search string. Alternatively, in the editor, highlight the string you want to find and press Ctrl+Shift+F . IntelliJ IDEA places the highlighted string into the search field.

How do I use structural search in IntelliJ?

From the main menu, select Edit | Find | Search Structurally. In the Structural Search dialog, under the Java | Class-based node, select All Fields of a Class which will look for all field declarations and click Find. As a result, in the Find tool window, IntelliJ IDEA shows all the fields declared in our Java code.

How to do a global search in IntelliJ?

From the main menu, select Navigate | Search Everywhere or press Shift twice to open the search window. By default, IntelliJ IDEA displays the list of recent files.


1 Answers

There is an inspection specifically for this:

  1. Go to Analyze -> Run Inspection By Name (or CtrlAltShiftI by default)
  2. Type enough of "Variable Type can by explicit" until you see it in the list, then select it
  3. Pick the scope you want to run the inspection over.
  4. In the 'Inspection Results' dialog, click the lightbulb button labelled 'Replace 'var' with explicit type'

You should carefully review the suggested fixes, as the inspection may well use the most specific type, e.g. ArrayList<Foo>, whereas it may well be more appropriate to use List<Foo> (there is no way for a tool to know that in all cases).

There is a complementary inspection called "Local variable type can be omitted", to replace explicit types with var.

like image 66
Andy Turner Avatar answered Oct 21 '22 11:10

Andy Turner