<分区>
这个问题在这里已经有了答案:
但是我读了一篇文章(Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?)。它发布了一个示例:
Supplier<Integer> incrementer(int start) {
return () -> start++;
}
代码会产生编译错误。该帖子试图解释原因并说:
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.
我看不懂它的解释,有两个问题:
- “在 start 方法参数被垃圾回收之前,lambda 不会运行”是什么意思?
- 为什么要复制?