简体   繁体   English

为什么递归调用此函数不会引发NullPointerException

[英]Why calling this function recursively does not throw a NullPointerException

My question comes from this thread . 我的问题来自这个话题

Consider this code: 考虑以下代码:

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));
    }
}

The output above is 8. 上面的输出是8。

What I don't get is that how fibLamdba is initialized? 我不知道如何初始化fibLamdba It seems that I totally miss how the method invocation is done because I though that this code would produce a NPE. 似乎我完全想念方法调用是如何完成的,因为我虽然这段代码会产生NPE。

Hope my question is clear 希望我的问题清楚

Your code is equivalent to 您的代码等同于

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));
}

By the time the apply is called fibLambda is assigned a value. 到名为fibLambdaapply fibLambda被分配一个值时。 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表达式不会捕获fibLambda的值,它只是注册该变量需要在适当的时候进行求值才能产生一个值。

Remember that a lambda expression doesn't execute the code appearing in its body. 请记住,lambda表达式不会执行其主体中出现的代码。 It's just a declaration, similar to how you declare an anonymous class instance. 这只是一个声明,类似于声明匿名类实例的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM