问题
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