How to refer a Lambda?

2019-02-18 17:00发布

How can I refer a Lambda from inside of it, if, for example, I need to use myLambda recursively?

myLambda -> {expression}
//           ^^^^^^^^^^ how can I refer to myLambda here?

3条回答
仙女界的扛把子
2楼-- · 2019-02-18 17:35

If you want to define a recursive function, use Java’s canonical way to implement a recursive function: a method:

public static int fib(int n) {
    return n==0? 0: n==1? 1: fib(n-1)+fib(n-2);
}

Then, if you need a instance fulfilling a functional interface you can use a method reference:

Function<Integer, Integer> fib = MyClass::fib;

or

IntUnaryOperator fib0=MyClass::fib;
查看更多
相关推荐>>
3楼-- · 2019-02-18 17:39

I misunderstood your question. Here's how you call a lambda expression recursively :

import java.util.function.*;
public class Test
{
    static Function<Integer, Integer> fib = null;

    public static void main (String[] args)
    {      
        fib = n ->
              n == 0 ? 0
              : n == 1 ? 1
              : fib.apply(n - 1) + fib.apply(n - 2); 
        System.out.println(fib.apply(8));
    }

}

This produces the output 21.

I borrowed the example from Jon Skeet and made the changes required to make it work.

You can find another example of a recursive lambda expression here.

查看更多
We Are One
4楼-- · 2019-02-18 17:49

If you mean you want to refer to the lambda expression you're defining within that lambda expression, I don't believe there's any such mechanism. I know of a few cases where it would be useful - recursive definitions, basically - but I don't believe it's supported.

The fact that you can't capture non-final variables in Java makes this even harder. For example:

// This doesn't compile because fib might not be initialized
Function<Integer, Integer> fib = n ->
      n == 0 ? 0
      : n == 1 ? 1
      : fib.apply(n - 1) + fib.apply(n - 2);

And:

// This doesn't compile because fib is non-final
Function<Integer, Integer> fib = null;
fib = n ->
      n == 0 ? 0
      : n == 1 ? 1
      : fib.apply(n - 1) + fib.apply(n - 2);

A Y-combinator would help here, but I don't have the energy to come up with an example in Java right now :(

查看更多
登录 后发表回答