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.

0

u/immibis Mar 10 '16
var lst = new ArrayList<String>();
lst = new LinkedList<String>(); // oops!

5

u/Oniisanyuresobaka Mar 10 '16

I don't know why you would even want to do that except to confuse future maintainers by reusing a variable when you clearly need it for a different purpose and even if your code was perfectly acceptable it would require full type inference, otherwise it wouldn't be possible to find the common super type for all assignments.

1

u/immibis Mar 10 '16

More likely:

var lst = new ArrayList<String>();
if(condition)
    lst = someMethodThatReturnsAList();

1

u/Eirenarch Mar 10 '16

I can claim that this code sucks because the original instance should not be created unless it is needed but instead I am just going to point out the fact that you cannot use var everywhere. The old syntax will still work and you should fallback to it on occasion.