Java - Create Recursive Lambda Expressions via anonymous inner class

Description

Create Recursive Lambda Expressions via anonymous inner class

Demo

import java.util.function.IntFunction;

public class Main {
  public static void main(String[] args) {
    IntFunction<Long> factorialCalc = new IntFunction<Long>() {
      @Override// www.  j ava  2 s.  co  m
      public Long apply(int n) {
        if (n < 0) {
          String msg = "Number must not be negative.";
          throw new IllegalArgumentException(msg);
        }

        if (n == 0) {
          return 1L;
        } else {
          return n * this.apply(n - 1);
        }
      }
    };
    int n = 5;
    long fact = factorialCalc.apply(n);
    System.out.println("Factorial of " + n + " is " + fact);
  }

}

Result

Related Topic