Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable extraction to var in Intellij IDEA

When extracting a variable (ctrl+alt+v) in Intellij IDEA with Java 11, I would like for the default to be that it is extracted to a var instead of the verbose type.

var home = "127.0.0.1";

instead of

String home = "127.0.0.1";

Is there a way to configure Intellij IDEA to do this?

like image 886
Jewels Avatar asked Jan 16 '19 14:01

Jewels


People also ask

How do I extract a method in IntelliJ?

To extract method:Press Ctrl+Alt+M or from the main menu, select Refactor | Extract | Method. In the dialog that opens, configure a method options, such as visibility, parameters, and so on. You can also change a name of the method if you need.

How do you extract variables?

Highlight the code you want to extract to a variable and press ⌥⌘V (macOS), or Ctrl+Alt+V (Windows/Linux), to extract it. Extracting parameters can be useful in improving the readability of your code.


2 Answers

Update

Feature has been implemented and available since IntelliJ IDEA 2019.1 release

https://youtrack.jetbrains.com/issue/IDEA-179176

Fix versions 2019.1 (191.6183.87)


This feature hasn't been adopted by IntelliJ IDEA yet.

I've submitted an explicit feature request at JetBrains' bug tracking system: https://youtrack.jetbrains.com/issue/IDEA-206367

Although, other similar tickets which have been submitted before, are not yet completed:

  • https://youtrack.jetbrains.com/issue/IDEA-179176
  • https://youtrack.jetbrains.com/issue/IDEA-198828


Alternative

However, you can somewhat achieve the desired behavior by using Custom Postfix Templates plugin, which allows to define your own custom postfix completion templates.

Statement like this:

enter image description here

Will be converted to:

enter image description here

To achieve this:

  • 1) Install Custom Postfix Templates plugin via Settings → Plugins → Browse Repositories.
  • 2) Press Shift+Alt+P (or go to menu Tools → Custom Postfix Templates → Edit Templates of Current Language) to open the custom postfix templates for the programming language in your current editor.
  • 3) Add the following template:

    .var : Extracts variable as inferred 'var' type
        NON_VOID                 →  var $VAR:suggestVariableName()$ = $expr$;
    

Restart IntelliJ and you're good to go.

Note. Existing postfix completion named 'var' exists in IntelliJ by default, you might want to disable the existing one (via Settings → Editor → General → Postfix Completion) or find another name for a new one.

like image 200
Mikhail Kholodkov Avatar answered Oct 12 '22 06:10

Mikhail Kholodkov


Jet Brains added this feature to Intellij 2019.1.1

variable extraction in Intellij 2019.1.1

like image 5
Jewels Avatar answered Oct 12 '22 04:10

Jewels