How can a Java lambda-expression reference itself?

后端 未结 3 1998
悲哀的现实
悲哀的现实 2021-02-04 16:27

I found this article to be very informative in comparison of old-style functions to new Java-8 lambda-functions and parallel processing. One thing I couldn\'t quite understand w

3条回答
  •  青春惊慌失措
    2021-02-04 16:45

    As said here, Java’s canonical way to implement a recursive function is a method:

    public static int fib(int n) {
        return n==0? 0: n==1? 1: fib(n-1)+fib(n-2);
    }
    

    Then, if you need a instance fulfilling a functional interface you can use a method reference:

    Function fib = MyClass::fib;
    

    or

    IntUnaryOperator fib0=MyClass::fib;
    

    This is the closest equivalent to a lambda expression as a lambda expression is not just syntactic sugar for a runtime generated class replacing the anonymous inner class but also for an anonymous method hosting the code of the single abstract method to implement.

    Using an ordinary recursive method turns the anonymous method into a named one while maintaining all other properties of lambda expressions. This differs from all other workarounds trying to give a lambda expression a reference to itself, like storing the instance into a field. These workarounds are not semantically equivalent (and less efficient).

提交回复
热议问题