This question already has an answer here:
But I read a post(Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?). It posts an example:
Supplier<Integer> incrementer(int start) {
return () -> start++;
}
The code will cast compile-error. The post tries to explain the reason and say:
The basic reason this won't compile is that the lambda is capturing the value of start, meaning making a copy of it. Forcing the variable to be final avoids giving the impression that incrementing start inside the lambda could actually modify the start method parameter. But, why does it make a copy? Well, notice that we are returning the lambda from our method. Thus, the lambda won't get run until after the start method parameter gets garbage collected. Java has to make a copy of start in order for this lambda to live outside of this method.
I cannot understand its explanation and I have two questions:
- What does "the lambda won't get run until after the start method parameter gets garbage collected" mean?
- Why does it make a copy?