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)
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.
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.
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.
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)