为什么递归调用此函数不会抛出NullPointerException [英] Why calling this function recursively does not throw a NullPointerException
问题描述
我的问题来自主题。
考虑以下代码:
public class Test {
static Function<Integer, Integer> fibLambda = null;
public static void main (String[] args) {
fibLambda = n -> n <= 2 ? 1 : fibLambda.apply(n - 1) + fibLambda.apply(n - 2);
System.out.println(fibLambda.apply(6));
}
}
上面的输出是8.
我没有得到的是 fibLamdba
是如何初始化的?似乎我完全错过了方法调用是如何完成的,因为我虽然这段代码会产生一个NPE。
What I don't get is that how fibLamdba
is initialized? It seems that I totally miss how the method invocation is done because I though that this code would produce a NPE.
希望我的问题很清楚
推荐答案
您的代码相当于
static Function<Integer, Integer> fibLambda = null;
public static void main(String[] args) {
fibLambda = n -> n <= 2 ? 1 : Example.fibLambda.apply(n - 1) + Example.fibLambda.apply(n - 2);
System.out.println(fibLambda.apply(6));
}
当适用时
被称为 fibLambda
被赋值。基本上,lambda表达式不捕获 fibLambda
的值,它只是注册该变量需要在适当的时刻进行评估以产生值。
By the time the apply
is called fibLambda
is assigned a value. Basically, the lambda expression doesn't capture the value of fibLambda
, it just registers that the variable needs to be evaluated at the appropriate moment to produce a value.
请记住,lambda表达式不会执行其正文中出现的代码。它只是一个声明,类似于声明匿名类实例的方式。
Remember that a lambda expression doesn't execute the code appearing in its body. It's just a declaration, similar to how you declare an anonymous class instance.
这篇关于为什么递归调用此函数不会抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!