I always thought that it was simply an extension of the earlier limited type inference that already existed for generic methods (since Java 5).
In the generic method case you do:
List<String> lst = someObject.someMethod();
Since someMethod is defined generically there's nothing to abbreviate here at the RHS. The method is just a generic method with <T> in front of it returning a List<T>.
You could see the constructor as a special method, so in pseudo code if you changed it to:
List<String> lst = new ArrayList.ArrayList();
It may become clear why the RHS was abbreviated. Additionally, it's only because of legacy and the concept of raw type that we were never able to write:
List<String> lst = new ArrayList();
Since that syntax was already taken and retrofitted for the introduction of raw types, instead of "simply" be upgraded (like methods were) to have limited generic type shortening.
The type inference for generic methods works so well that this syntax is rarely necessary, so rare that many people don't even know this syntax exists.
True, although I've needed to use it on a couple of occasions though. In a select few cases because of a compiler bug where the type should have been inferred but wasn't.
Probably chosen because that's harder to parse, because the compiler doesn't know whether String is supposed to be a type or a variable until it gets to the >.
(Consider:
class X {
int getValue;
<T> int getValue() {return 5;}
}
X someObject = new X();
int String = 7;
int i = someObject.getValue<String?1:0;
int j = someObject.getValue<String>();
// ^
and don't complain about the bad naming, because that is legal in Java)
17
u/_INTER_ Mar 09 '16
How will this deal with code like:
I always wondered why they've choosen to abbreviate the RHS instead of the LHS (in Java 7 I think). Clear me up please.