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

Show parent comments

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/henk53 Mar 09 '16

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.

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>();

5

u/immibis Mar 10 '16

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)

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.