簡體   English   中英

為什么在Groovy閉包中設置的實例變量的值在其外部不可見?

[英]Why is the value of the instance variable set in a Groovy closure not visible outside of it?

為什么methodA()打印set within run而不是set within closureset 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"
    }
}

參考

閉包 - 正式定義

同時,變量仍然可以正常地用於封閉范圍,因此閉包可以讀取/更改任何這樣的值,並且來自外部范圍的代碼可以讀取/更改相同的變量。

版本

  • Groovy 1.8.6
  • Groovy-Eclipse插件2.8.0
  • Eclipse Platform 3.8.1

用戶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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM