gpt4 book ai didi

java - 为什么 lambda 中使用的局部变量必须是最终的或实际上是最终的?

转载 作者:行者123 更新时间:2023-11-29 04:06:11 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:

但是我读了一篇文章(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.

我看不懂它的解释,有两个问题:

  1. “在 start 方法参数被垃圾回收之前,lambda 不会运行”是什么意思?
  2. 为什么要复制?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com