[英]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.