Consider the following code fragment:
public static Object o = new Object();
public static Callable x1() {
Object x = o;
return () -> x;
}
publi
There is no way for the compiler to optimise x1()
to return the same lambda -- the behaviour would then be different. Since o
is not final, the lambda returned needs to capture the state of that field (with the x
variable) as its value could change between calling x1()
and invoking the returned lambda.
That's not to say that there aren't situations where the compiler theoretically could reuse the instance but doesn't (the other answers give some insight into that) -- only that this isn't one of those cases.