Search code examples
javaintellij-idea

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.


Solution

  • There is an inspection specifically for this:

    1. Go to Code -> Analyze Code -> Run Inspection by Name... (or CtrlAltShiftI by default)
    2. Type enough of "Variable Type can be 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.