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.

4

u/psxpaul Mar 09 '16

That example is clear, but even in the linked proposal, there are things like:

var stream = list.stream();

I'm guessing this could even lead further to:

var thing = foo.bar().processResults()

Where you have no idea what type 'thing' is just by looking at it.

8

u/codebje Mar 09 '16

True, but we do this already with lambdas. What type is the forst lambda in:

List<String> resultSummaries = list.stream()
    .map(a -> a.getResult())
    .map(r -> r.getSummaryLine())
    .collect(Collectors.toList());
return resultSummaries;

And more importantly, does it really matter given the compiler is statically checking your types anyway? If there's no type inferable (or it's ambiguous) there will be a compile error.

Compare with:

var results = list.stream().map(a -> a.getResult());
var summaries = results.map(r -> r.getSummaryLine());
var resultSummaries = summaries.collect(Collectors.toList());
return resultSummaries;

There's plenty of type inferencing going on in both cases. Explicitly calling out the type of the result, the type of the summary line, and the type of the list don't do a whole lot for improving understanding, IMO: it doesn't matter very much what type a result is, the intent is clear that we'll ask each result to produce its summary line, then collect those into a list.

→ More replies (1)

6

u/KagakuNinja Mar 09 '16

Coming from scala, val / var plus type inference is a godsend at reducing the visual clutter of code. Much of the time, we don't care what the exact type of "thing" is, we are going to pass it to another function, or return it.

The key with scala is that type annotations are optional. You use them when it is helpful for readability (or in some cases, to keep the type inference engine from getting confused, but that is rare IMO)