gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:09:36 24 4
gpt4 key购买 nike

当我写这段代码时,我得到了一个编译时错误,它说:“lambda 中的变量必须是最终的或实际上是最终的”

现在,我得到了从行中删除 i 的方法:

futureLists.add(executorService.submit( () -> "Hello world"+ i));

解决了这个问题。

但我想知道为什么会有这样的要求?

根据 JLS , 它只说:

Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

但它没有说明为什么存在这样的要求。但为什么 Java 工程师要对 lambda 强制执行这样的要求?

public class test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);

List<Future<String>> futureLists = new ArrayList<>();

for (int i = 0; i < 20; i++) {
futureLists.add(executorService.submit( () -> "Hello world" + i));
}

for (Future<String> itr:futureLists) {
System.out.println(itr.get());
}
}
}

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