【发布时间】:2016-04-25 17:14:59
【问题描述】:
在 groovy 中确保类变量不受闭包影响的命令是什么?正如我们所知,闭包捕获了它所在的环境。因此,例如,如果我有一个闭包递增一个整数类变量,那么该变量会针对该类进行更改。我想要的是闭包拥有自己的变量副本,因此它不会影响类变量。可能吗?例如,在 Objective C 中,我们将使用 __Block 命令,这将使块能够更改捕获变量的值。现在,在我的情况下,我要求与 __Block 相反,因为闭包已经改变了它们作用域的变量。
让我们看一个我想要的清晰示例:
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 不会知道它的环境,对吧?但是可以说我只想让变量不知道它的环境而其他人应该知道,那么 lambda 就不好了。
【问题讨论】:
-
以这种方式编写代码将无法调试,将来你会恨你现在。为什么不将参数传递给返回闭包的方法?
-
感谢您的反馈,这只是我想做的一个例子,我做了。它在 Groovy 版本:2.4.1 JVM:1.8.0_45 上运行良好,只需剪切和粘贴。