JEP 302: Underscore as enhanced for loop parameter?

Tagir Valeev amaembo at gmail.com
Thu Oct 5 05:21:01 UTC 2017


Hello!

I think underscore could be allowed as an enhanced for parameter. In
rare cases it's necessary to iterate over Iterable without using the
elements like here:

long countElements(Iterable<?> iterable) {
  long count = 0;
  for(Object _ : iterable) count++;
  return count;
}

Here we have a place where we're syntactically forced to declare a
variable, but we don't need one. Similarly to a catch block this
perfectly fits the underscore use cases. This would also help to
perform code static analysis. It's common for IDEs to warn if a loop
variable is unused (which could be a bug like another variable is used
instead by mistake). Using underscore we explicitly say that we don't
need a variable here. In IntelliJ IDEA we suggest using an "ignored"
name in such case, but it's still a valid name and can be used
accidentally or clashed with another name.

Sorry if this was already discussed, I wasn't able to find any public
discussions on this topic.

With best regards,
Tagir Valeev.


More information about the amber-spec-experts mailing list