groovy中確保類變量不受閉包影響的命令是什麼?正如我們所知,一個閉包捕獲了它所包含的環境。因此,如果我有一個閉包遞增一個整數類變量,那麼該變量會針對該類的變化進行更改。我想要的是閉包擁有自己的變量COPY,所以它不會影響類變量,是否有可能在Objective C中,例如,我們將使用__Block命令,這將使塊能夠更改捕獲的變量的值,現在我要求__block的在我的情況相反的閉包已經改變了他們在作用域變量如何使閉包有其自己的副本變量-does groovy有lambda
讓我們看看在我想要的一個明顯的例子:
def class myCoolClass {
def x=1
def myMethodThatReturnsClosure(){
//lets return a closure who's scope will include the x=1
myClosure
}
def showMeXFromMyCoolClass(){
println "this is x from myCoolClass:$x"
}
def myClosure={
println "im printing x:$x"
//lets change x now from within closure
x++
}
}
def x = new myCoolClass();
def c=x.myMethodThatReturnsClosure();
c(); //we are changing x ...x = 1
c(); //we are changing x again ...x = 2
c(); //we are changing x again ...x = 3
x.showMeXFromMyCoolClass(); //...x = 4
//i dont want x to be 4 in the last call, i want x to be 1.
//i want it unchanged. how to tell closure to take its own copy
我知道在groovy封閉知道它的環境。它圍繞它所包裹的功能「關閉」。那麼groovy中是否有lambda?我認爲拉姆達不會知道它的環境吧?但讓我說我只想要變量不知道它的環境和其他人應該,然後lambda不會好。
用這種方式編寫代碼將無法調試,而且將來你會恨你。爲什麼不將參數傳遞給返回閉包的方法? –
感謝您的反饋,它只是我想要做的一個例子,我做到了。並且它在Groovy Version:2.4.1 JVM:1.8.0_45上運行良好,只需剪切和粘貼。 – j2emanue