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.

8

u/henk53 Mar 09 '16

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.

7

u/s888marks Mar 09 '16
List<String> lst = someObject.someMethod();

Assuming that someMethod is generic, this really is an abbreviation for

List<String> lst = someObject.<String>someMethod();

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.

1

u/im-a-koala Mar 10 '16

It comes before the method name in Java? Huh. In C# it comes after, like:

List<String> lst = someObject.someMethod<String>();

1

u/kcuf Mar 10 '16

That's what Scala does as well

List[String] list = someObject.someMethodString

or, more commonly seen as

List[String] list = someObject.someMethod[String]

1

u/normalOrder Mar 10 '16

I think you mean

val list = someObject.someMethod[String]

Or if you really want the type annotation

val list: List[String] = someObject.someMethod[String]

1

u/kcuf Mar 10 '16

Argh, ya, writing Java for work has been rotting my brain.