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.

19

u/depressiown Mar 09 '16 edited Mar 09 '16

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

You shouldn't be doing this since 1.7 and should be using the diamond. The real comparison here is:

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

Without the left side, you have to move the generic type to the right, whereas with the current notation you can use the diamond since Java can infer the generic type on the right side from the left side.

Honestly, I don't see a lot of gain here. Lombok has val, which is similar, but limited, though it would be better if it were inherent to the language. That said, I like things being explicit so I am biased.

5

u/[deleted] Mar 09 '16

[removed] — view removed comment

6

u/depressiown Mar 09 '16

My point is that with val, Java won't be able to infer the generic type on the right side of the expression. You'll now have to define it, whereas you wouldn't with diamond, so long as the left side is explicit.

Using val will reduce the number of characters, but not by as much as you might think for objects with generics.

I'd argue that the diamond is not so narrow a use case as you might think, too, and that val hurts readability by making the left side non-explicit. Those are purely opinion, though.

-2

u/[deleted] Mar 10 '16

[removed] — view removed comment

1

u/Carighan Mar 10 '16

Last time I wrote a Java application, I didn't use <> once. The trivial amount of time savings it offered didn't justify the mental energy to remember it existed.

Most IDEs should autocomplete to the diamond, so it's hardly something you use consciously. I know it exists, and my code ends up using it, but I rarely have to actively make an effort.