How to refer a Lambda?

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?
Jon Skeet
people
quotationmark

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 :(

people

See more on this question at Stackoverflow