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?
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?
If you want to define a recursive function, use Java’s canonical way to implement a recursive function: a method:
Then, if you need a instance fulfilling a functional
interface
you can use a method reference:or
I misunderstood your question. Here's how you call a lambda expression recursively :
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.
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:
And:
A Y-combinator would help here, but I don't have the energy to come up with an example in Java right now :(