No 'fold left' without a combiner ?

Paul Sandoz paul.sandoz at oracle.com
Mon Sep 9 06:48:00 PDT 2013


On Sep 8, 2013, at 6:18 PM, Remi Forax <forax at univ-mlv.fr> wrote:

> Did I say that I will send you an email to the EG lists each time I will be annoyed by visibility of lambda parameter rule ?
> 
> ArrayList<Advice> advices = ...
> AnnotatedElement annotatedElement = ...
> MethodHandle mh = advices.stream().reduce(impl, (mh, advice) -> advice.chain(annotatedElement, mh), null);
> 
> In fact, there is another issue, (the real reason of this email), this code throws a NPE at runtime because I use null as combiner.
> It seems there is no way to express a left fold on values (different from T) when the values can not be combined.
> 
> I've fixed the issue by writing,
>  MethodHandle target = advices.stream().reduce(impl,
>      (mh, advice) -> advice.chain(annotatedElement, mh),
>      (_1, _2) -> { throw new AssertionError(); } );
> but it's clearly ugly.
> 

Yes, and it will barf for parallel streams.

You might be better off using an explicit forEach or writing a static foldLeft utility method that internally calls sequential().

Paul.


More information about the lambda-libs-spec-experts mailing list