为什么Groovy闭包引用带有引用的for循环迭代计数器 [英] Why groovy closure refers to for loop iteration counter with reference

查看:80
本文介绍了为什么Groovy闭包引用带有引用的for循环迭代计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么以下两个片段输出不同的结果。看起来迭代计数器是由闭包处理的特殊情况。

I am wondering why the following two snippets output different results. It looks like the iteration counter is a special case handled by closure.

int i = 1
def closures = (1..3).collect {
    return { println i; ++i }
}

for (int j = 0; j < 3; ++j) {
    closures += { println j }
}

closures*.call()

1
2
3
3
3
3


推荐答案

这是何时更新变量的问题

It's a question of when the variable is updated

在第一个示例中, i 仅在执行闭包时递增,因此即使每个闭包都绑定到同一实例 i 的每个输出都是不同的

In the first example, i is only incremented when the closure is executed, so even though each closure is bound to the same instance of i, each output is different

在第二个示例中, j 在闭包之外递增,因此当您运行它们时, for 循环已经完成,并且值 j 3

In the second example, j is incremented outside the closures, so by the time you run them, the for loop has finished, and the value of j is 3

这篇关于为什么Groovy闭包引用带有引用的for循环迭代计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆