How to pass lambda?

How can I reference the Lambda from the inside if, for example, I need to use myLambda recursively?

 myLambda -> {expression} // ^^^^^^^^^^ how can I refer to myLambda here? 
+3
source share
3 answers

I misunderstood your question. Here you recursively call the lambda expression:

 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)); } } 

Returns result 21.

I borrowed an example from Jon Skeet and made the changes necessary for it to work.

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

+4
source

If you mean that you want to refer to the lambda expression that you define inside this lambda expression, I don’t think there is such a mechanism. I know of a few cases where this would be useful - recursive definitions, basically - but I don't believe this is supported.

The fact that you cannot capture non-finite variables in Java makes this even more difficult. For instance:

 // 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 will help here, but I don't have the energy to come up with an example in Java right now :(

+7
source

If you want to define a recursive function, use the canonical Javas method to implement the recursive function: method:

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

Then, if you need an instance that executes a functional interface , you can use the method reference:

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

or

 IntUnaryOperator fib0=MyClass::fib; 
+1
source

Source: https://habr.com/ru/post/980486/


All Articles