title: Recursive lambda expressions in Java 8
body: <p>I just wanted to define a Java 8 lambda expression recursively.</p>
  
  <p>The <a href="http://www.lambdafaq.org/can-lambda-expressions-be-used-to-define-recursive-functions/#comment-1351654">Lambda FAQ</a> mentions that one can define a recursive lambda expression only during (static) field initialization. </p>
  
  <p>But I get a compiler error in IntelliJ (javac just reports an error without a message):  </p>
  
  <blockquote>
    <p>java: self-reference in initializer</p>
  </blockquote>
  
  <p>If I try to write something like:</p>
  
  <pre><code>static UnaryOperator&lt;Integer&gt; f = i -&gt; i == 0 ? 1 : i * f.apply( i - 1);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>UnaryOperator&lt;Integer&gt; f = i -&gt; i == 0 ? 1 : i * f.apply( i - 1);
  </code></pre>
  
  <p>One way I found to make it work was to use an array for referencing the lambda effectively tricks the java compiler:</p>
  
  <pre><code>import java.util.function.UnaryOperator;
  
  public class RecursiveLambdaExample {
  
      public static void main(String[] args) {
  
          UnaryOperator&lt;Integer&gt;[] fac = new UnaryOperator[1];
          fac[0] = i -&gt; i == 0 ? 1 : i * fac[0].apply( i - 1);
  
          UnaryOperator&lt;Integer&gt; factorial = fac[0];
  
          System.out.println(factorial.apply(5));
      }
  }
  </code></pre>
  
  <p>Is there another trick to define recursive lambda expression?</p>