Iterable::forEach not returning Iterable

Brian Goetz brian.goetz at oracle.com
Thu May 17 07:04:54 PDT 2012


Your observation that Iterables.forEach returns the Iterable is simply 
vestigial evidence that we originally tried it as you suggest and fell 
back to the current API.

The problem is one of semantics.  The semantics of forEach is eager; an 
eager operation doesn't return until all the elements have been 
processed.  While a "lazy forEach" is possible, it is less natural (and 
therefore more confusing), and, as you point out, the compelling case 
for a lazy forEach is debugging.  Debugging is important, but not so 
enough as to distort the semantics of the model.

We have toyed with the idea of a "tee(Block)" method for introducing the 
desired debuggability (one of the biggest challenges in mentally 
shifting to laziness is debugging -- the operations are interleaved and 
there is no natural place to put the breakpoint and see an intermediate 
computation.)  But we are focusing on higher-order issues first, such as 
how things fit into the collection framework, how we'll deal with 
primitives, etc.

On 5/17/2012 6:33 AM, Tomasz Kowalczewski wrote:
> Hi,
>
> I was trying out the new jdk8 build with lambdas and while doing some
> simple towards-lamda-refactoring I stumbled on following use case:
>
> List<File>  files...
> files.filter( File::isFile ).filter( ... ).map( ConfigurationFile::new );
>
> I wanted to inject some debugging code inside this chain using forEach
> and realized that it returns void and not Iterable. Its default
> delegates to Iterables::forEach that returns Interable, so I guess it
> is just a matter of deciding if forEach should seal the pipe or allow
> more processing.
>
> Based on my example I think there is a great value in changing the
> return type from void as in my opinion it will be harder to debug and
> step through such lambdanized code than through several (ugly)
> for-each loops doing same work.
>
> P.S.: Atttaching eclipse debugger to this code being run in a simple
> main() instantly crashes the debugged JVM. But I guess debugging is
> not yet supported anyway :)
>


More information about the lambda-dev mailing list