Why calling this function recursively does not throw a NullPointerException

我们两清 提交于 2020-01-15 06:42:07

问题


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.

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.

Hope my question is clear


回答1:


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. 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.

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.



来源:https://stackoverflow.com/questions/27769808/why-calling-this-function-recursively-does-not-throw-a-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!