recursive lambdas

Remi Forax forax at univ-mlv.fr
Mon Sep 24 07:57:47 PDT 2012


On 09/24/2012 04:50 PM, Aleksey Shipilev wrote:
> Let me be more clear. As I understand the spec prohibits this:
>
>     void test() {
>        IntUnaryOperator fib =
>            (n) -> (n < 2) ? 1 : fib.operate(n - 1) + fib.operate(n - 2);
>     }
>
> ...but still allows this (still a recursive lambda):
>
>     public IntUnaryOperator fib =
>           (n) -> (n < 2) ? 1 : fib.operate(n - 1) + fib.operate(n - 2);
>
> ...because the current JLS does not prohibit this. Also, the plain old
> inner classes work as well:
>
>      public IntUnaryOperator fib =
>              new IntUnaryOperator() {
>                  @Override
>                  public int operate(int n) {
>                      return (n < 2) ? 1 :
>                           fib.operate(n - 1) + fib.operate(n - 2);
>                  }
>              };
>
>      public interface IntUnaryOperator {
>          int operate(int v);
>      }
>
>
> Am I correct?

yes, the former tries to capture a local variable which is not yet 
initialized while the later capture this thus can access to this.fib 
when called.

cheers,
Rémi



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