Iterable::forEach not returning Iterable

David Conrad drconrad at gmail.com
Tue May 22 11:37:43 PDT 2012


On Thu, 17 May 2012 12:33:59 +0200, Tomasz Kowalczewski <
tomasz.kowalczewski at gmail.com> wrote:

> ... while doing some simple towards-lambda-refactoring I stumbled on:
>
> 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.
>

On Thu, 17 May 2012 16:31:40 +0200, R?mi Forax <forax at univ-mlv.fr> wrote:

> On 05/17/2012 04:05 PM, Brian Goetz wrote:
> > Of course, no one would write production code like this.  Mappers are
> > supposed to be side-effect-free.  But it is an acceptable sin for
> > temporary debugging code.
>
> Haskell guys, please don't read ...
>
> but logging is side effect free until you read the log in the program.
>

That's what I say, too, but they never listen !


> R?mi
>
> >
> > On 5/17/2012 9:26 AM, Remi Forax wrote:
> >> You can use
> >>    map(it ->  {
> >>       Log.log(it);
> >>       return it;
> >>     }).
> >> instead of forEach.
> >>
> >> R?mi
> >>
>

If you use it often, a little helper method may make it easier to read:

    public static <T> Mapper<T, T> tee(Block<T> block) {
        return t -> { block.apply(t); return t; };
    }

And then Thomasz's example becomes:

List<File> files...
files.filter( File::isFile ).map(tee((File f) -> { Log.log(f); return f;
})).filter( ... ).map( ConfigurationFile::new );

I had to qualify the type of the lambda parameter, though; the compiler
couldn't infer it. Ah, well.

Cheers, Rémi !
David


More information about the lambda-dev mailing list