Java 8中的递归lambda表达式 [英] Recursive lambda expressions in Java 8
问题描述
我只是想以递归方式定义Java 8 lambda表达式。
I just wanted to define a Java 8 lambda expression recursively.
Lambda FAQ 提到只能在(静态)字段初始化期间定义递归lambda表达式。
The Lambda FAQ mentions that one can define a recursive lambda expression only during (static) field initialization.
但我在IntelliJ中遇到编译器错误(javac只报告没有消息的错误):
But I get a compiler error in IntelliJ (javac just reports an error without a message):
java:初始值设定项中的自引用
java: self-reference in initializer
如果我尝试写类似:
static UnaryOperator<Integer> f = i -> i == 0 ? 1 : i * f.apply( i - 1);
或
UnaryOperator<Integer> f = i -> i == 0 ? 1 : i * f.apply( i - 1);
我发现使其工作的一种方法是使用数组来引用lambda有效地欺骗java编译器:
One way I found to make it work was to use an array for referencing the lambda effectively tricks the java compiler:
import java.util.function.UnaryOperator;
public class RecursiveLambdaExample {
public static void main(String[] args) {
UnaryOperator<Integer>[] fac = new UnaryOperator[1];
fac[0] = i -> i == 0 ? 1 : i * fac[0].apply( i - 1);
UnaryOperator<Integer> factorial = fac[0];
System.out.println(factorial.apply(5));
}
}
还有另一种定义递归lambda表达式的技巧吗? / p>
Is there another trick to define recursive lambda expression?
推荐答案
您可以通过完全限定递归引用的字段名称来使其工作。此版本编译时没有任何错误:
You can make it work by fully-qualifying the field name that you're referencing recursively. This version compiles without any error:
import java.util.function.UnaryOperator;
public class RecursiveLambdaExample {
static UnaryOperator<Integer> fac = i -> i == 0 ? 1 : i * RecursiveLambdaExample.fac.apply( i - 1);
UnaryOperator<Integer> f = i -> i == 0 ? 1 : i * this.f.apply( i - 1);
public static void main(String[] args) {
System.out.println(new RecursiveLambdaExample().f.apply(5));
System.out.println(fac.apply(5));
}
}
相关:为什么Java 8中的lambdas不允许对匿名类没有的成员变量进行前向引用?
这篇关于Java 8中的递归lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!