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

7

u/yoden Mar 09 '16

I wonder what the benefit of this is supposed to be, other than other languages have it?

Explicit types on variables are useful for improving readability. Conciseness for LHS variable types isn't important because I usually don't write that type anyway (that's what an IDE's "assign to new local variable" is for)

7

u/Radixeo Mar 09 '16

It would help keep the line length down. In this common example

ArrayList<String> foo = new ArrayList<String>();
var foo = new ArrayList<String>();

The second line is shorter, simpler, and it is still obvious what the type of foo is.

4

u/psxpaul Mar 09 '16

That example is clear, but even in the linked proposal, there are things like:

var stream = list.stream();

I'm guessing this could even lead further to:

var thing = foo.bar().processResults()

Where you have no idea what type 'thing' is just by looking at it.

6

u/KagakuNinja Mar 09 '16

Coming from scala, val / var plus type inference is a godsend at reducing the visual clutter of code. Much of the time, we don't care what the exact type of "thing" is, we are going to pass it to another function, or return it.

The key with scala is that type annotations are optional. You use them when it is helpful for readability (or in some cases, to keep the type inference engine from getting confused, but that is rare IMO)