[英]Why is the value of the instance variable set in a Groovy closure not visible outside of it?
题
为什么methodA()
打印set within run
而不是set within closure
中set within closure
?
代码示例
class GroovyClosureVariableScopingTest extends Script {
String s
Object run() {
s = "set within run"
println "value of s in run(): $s"
[1].each {
s = "set within closure"
println "value of s in each()-closure: $s"
methodA()
}
}
void methodA() {
println "value of s in methodA(): $s"
}
}
实际输出
value of s in run(): set within run
value of s in each()-closure: set within closure
value of s in methodA(): set within run // <- Surprised to see the original value
预期产出
value of s in run(): set in run
value of s in each()-closure: set within closure
value of s in methodA(): set within closure // <- Whould have expected this value
精
我还不太清楚变量作用域如何在上面的例子中起作用。 我本来希望s
是类的一个属性(一个公共实例变量),我认为我从each
-closure中分配了一个值,这个值将被保留。 但事实似乎并非如此。
为什么s
不保留从闭包中分配的值?
解决方案/解决方法
将s
作为参数传递给methodA()
有效。 请参阅// Change
评论的行。
class GroovyClosureVariableScopingTest extends Script {
String s
Object run() {
s = "set within run"
println "value of s in run(): $s"
[1].each {
s = "set within closure"
println "value of s in each()-closure: $s"
methodA(s) // Change
}
}
void methodA(s) { // Change
println "value of s in methodA(): $s"
}
}
参考
同时,变量仍然可以正常地用于封闭范围,因此闭包可以读取/更改任何这样的值,并且来自外部范围的代码可以读取/更改相同的变量。
版本
用户cfrick确认它在他的机器上工作后,我从控制台运行它确实有效。
从控制台
C:\temp>java -jar C:\...\lib\groovy-all-1.8.6.jar C:\temp\GroovyClosureVariableScopingTest.groovy
value of s in run(): set within run
value of s in each()-closure: set within closure
value of s in methodA(): set within closure // <- Here
使用干净的Eclipse安装
但我仍然没有得到原始脚本与干净安装运行
摘要
我仍然不知道为什么它不起作用 - 即使是干净的Eclipse安装。 但是,它可以在控制台上运行,它可以在cfrick的机器上运行,并且有一个解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.