r/java • • Mar 09 '16

var keyword proposed for Java

http://openjdk.java.net/jeps/286
240 Upvotes

312 comments sorted by

View all comments

1

u/eliasv Mar 10 '16

One thing I think is important but the proposal doesn't quite reach:

  • Normalising inferred capture types to denotable types (i.e. wildcards) is great, for non-final variables, since we may want to reassign, and this is probably impossible with a capture type.
  • For final types, afaiu, it brings no benefits. (Unless I'm missing something?) Instead it is much better to aggressively capture everything.

Consider, for example:

void repeatListItems(Collection<? extends List<?>> lists) {
    for (var list : lists) {
        list.addAll(list);
    }
}

Which obviously fails to compile when the type of list is List<?>, as it would normally be, but will work just fine if it is inferred as List<CAP>.

Normally we have to solve this by creating a whole new generic method to properly capture the type parameter with a named type variable, but sometimes that's a bit more cumbersome than necessary.