Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

Can lambda expressions be used to define recursive functions?

Yes, provided that the recursive call uses a name defined in the enclosing environment of the lambda. This means that recursive definitions can only be made in the context of variable assignment and, in fact—given the assignment-before-use rule for local variables—only of instance or static variable assignment. So, in the following example, factorial must be declared as an instance or static variable.

Example

    UnaryOperator<Integer> factorial = i -> i == 0 ? 1 : i * factorial.apply( i - 1 );

Earlier versions of the specification allowed local variables to be used as well. There
is some discussion about the reversal of this decision in the comments on this page.