Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infer variable type in Java / Eclipse, like C#'s "var"

I like "var" from C# and "def" from Groovy, and I find writing out types in Java to be a pain.

Say I'm writing code like:

List<LongTypeName> results = new ArrayList<LongTypeName>();

or

Map<TypeNameOne,TypeNameTwo> someLookup = fetchMeMyLookup();

What's the easiest way to get this done in Java + Eclipse?

I'm especially interested in the case where I'm not 100% sure what the type will be when I start the line.

My current strategy is to always declare variables as "int", then go back to the start of the line and do "ctrl-1", and accept the type that Eclipse has inferred. Is there any better alternative?

What I would love is to be able to type "def" or "var" and have Eclipse auto-correct this to the correct type as soon as it can figure it out.

(Maybe I should just be programming in Groovy)

like image 974
Rich Avatar asked Oct 20 '11 14:10

Rich


2 Answers

  1. Type new ArrayList<LongTypeName>();
  2. Type Ctrl+2+L to create a new local variable

Both type type are 'active' - you can tab through them an cycle through selections. In this example, the name proposals are list and arrayList and the type proposals are all possible interfaces and superclasses of ArrayList<String>, : List<String, Collection<String> etc.

screenshot

like image 151
Robert Munteanu Avatar answered Nov 01 '22 16:11

Robert Munteanu


Type:

someLookup = fetchMeMyLookup();

Then click on someLookup and hit Ctrl+1 for the quick fix of "Create local variable someLookup"

like image 25
Jon Skeet Avatar answered Nov 01 '22 16:11

Jon Skeet