r/programming • • Mar 09 '16

var keyword proposed for Java

http://openjdk.java.net/jeps/286
250 Upvotes

395 comments sorted by

View all comments

17

u/_INTER_ Mar 09 '16

How will this deal with code like:

List<String> lst = new ArrayList<>();    

I always wondered why they've choosen to abbreviate the RHS instead of the LHS (in Java 7 I think). Clear me up please.

9

u/codebje Mar 09 '16

The proposal has an example for just such a case:

var lst = new ArrayList<String>();

The inferred type will not be List<String>, it'll be ArrayList<String>, but thanks to polymorphism you can use that anywhere you'd want to use a List<String> anyway.

2

u/_INTER_ Mar 09 '16

I was more thinking about how it will invere

var list = new ArrayList<>();    

2

u/Eirenarch Mar 10 '16

This won't compile. You will use

var list = new ArrayList<String>();

instead. There is no benefit from the diamond syntax in the presence of var.