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

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.

0

u/yoden Mar 10 '16

The difference is the chained lambda isn't used to type other things. For example, the inferred type of a "var" will determine what functions are called when functions are overloaded.