138

In Eclipse if you have a method:

String MyObject.getValue();

When using this you can go:

MyObject.getValue(); 

If you cursor is on the line and you hit CTRL + 1 you get a context menu to 'assign a new local variable', resulting in the following:

String value = MyObject.getValue(); 

Can you do this as easily in IntelliJ? I've search the net but without success.

Jasper
  • 2,166
  • 4
  • 30
  • 50
JARC
  • 5,288
  • 8
  • 38
  • 43
  • 10
    ProTip if you don't remember a keyboard shortcut: Wherever you are in the code, if you hit [Ctrl] + [Shift] + [A] ([cmd] + [Shift] + [A] in Mac) it will show a list of actions by name, you can type the action you want to do (e.g. Variable) and execute it – Christian García Jan 31 '14 at 23:48
  • 2
    In Eclipse, it's faster to do "Ctrl-2 l" (lower-case L). – Duncan Jones Dec 19 '14 at 21:31

3 Answers3

221

Yep! This is the Introduce Variable refactoring. By default, select some text, and then hit Ctrl + Alt + V (for Mac: ++V). If the expression is incomplete or invalid, IntelliJ will still make a good guess about what you meant and try to fix it for you.

soshial
  • 5,906
  • 6
  • 32
  • 40
John Feminella
  • 303,634
  • 46
  • 339
  • 357
58

IntelliJ 13.1 introduced Postfix completion.

With Postfix Completion you can introduce a local variable by typing:

MyObject.getValue().var

and pressing ctrl + space or enter.

It even works inside other statements. For example:

foo.someMethod(myObject.getValue().var);
micha
  • 47,774
  • 16
  • 73
  • 80
14

for mac users: alt + enter at the position where you want to generate your variable

Olivier Royo
  • 810
  • 10
  • 13
  • This is my go-to method. Is there a way you know of to default to a typed instance? I often have to alt + enter again and select "Add type annotation" – JaredEzz Apr 08 '22 at 17:53