StKiller
StKiller

Reputation: 7951

Intellij Idea - automatically add final keyword to the generated variables

The new introduced code convention require to use the "final" keyword where possible.

The question is - is there a possibility to automatically generate the variables with this keyword ? For example - I select a code fragment:

"bla"+"bla"+"bla"

and press ctrl+alt+v - the IDE generates a variable like this:

String blaString = "bla"+"bla"+"bla";

but I need it to be

final String blaString = "bla"+"bla"+"bla";

P.S. I know about inspections and the possibility "fix them all", but it can't be used everywhere as there is a lot of old code that shouldn't be refactored without reason.

Upvotes: 96

Views: 44909

Answers (5)

Jake Walsh
Jake Walsh

Reputation: 3869

Go to Settings/Preferences -> Editor -> Code Style -> Java -> Code Generation and enable "Make generated local variables final" and "Make generated parameters final" in the "Final modifier" section. You can also try searching for "final" in preferences.

Upvotes: 148

Justin Reeves
Justin Reeves

Reputation: 26

I wasn't able to disable this behavior from the Code Style settings, but Steven Bayer's solution worked for me. I'm providing a screenshot for clarity on what he's referring to. Uncheck the "Declare final" box.

enter image description here

Upvotes: 0

Steven Bayer
Steven Bayer

Reputation: 2127

After selecting "introduce local variable" there is a little gear to the right of the variable name. Click that and check "Declare final". That variable will be marked as final and Intellij will remember your preference until changed.

Upvotes: 8

Viraj Pai
Viraj Pai

Reputation: 71

For Windows User;

Go to File -> Settings -> Editor -> Code Style -> Select Preferred Language (Java) -> Checkbox -> Make generated local variables final, Make generated parameters final -> Apply -> OK

Upvotes: 5

Andrey
Andrey

Reputation: 9072

In IntelliJ 14.1.3

  1. Preferences > Editor > Code Style > Java
  2. To the far right ,there's a tab called Code Generation
  3. In the section called Final Modifier there are two choices:
    • Make generated local variables final
    • Make generated parameters final

Upvotes: 57

Related Questions