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

Exit above 8.

I do not understand how fibLamdba initialized? It seems that I will completely miss how the method call is executed, because although this code will create an NPE.

Hope my question is clear.

+2
source share
1 answer

Your code is equivalent

 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 apply is called fibLambda , a value is assigned. Basically, the lambda expression does not capture the value of fibLambda , it simply registers that the variable must be evaluated at the right time to get the value.

Remember that the lambda expression does not execute the code that appears in its body. This is just a declaration, similar to how you declare an instance of an anonymous class.

+6
source

Source: https://habr.com/ru/post/980488/


All Articles