Groovy:如何获得一个?private的值?闭包变量
我有一个非常有效的闭包,但有时我想得到我在闭包中定义的临时变量的最终值。例如:Groovy:如何获得一个?private的值?闭包变量,groovy,scope,closures,private,Groovy,Scope,Closures,Private,我有一个非常有效的闭包,但有时我想得到我在闭包中定义的临时变量的最终值。例如: def someClosure = {Number input-> def howDoIGetThis = input + 4 return 2 * input } def normalWay = someClosure(2) assert normalWay == 4 def myFantasy = someClosure(2).howDoIGetThis assert myFantasy ==
def someClosure = {Number input->
def howDoIGetThis = input + 4
return 2 * input
}
def normalWay = someClosure(2)
assert normalWay == 4
def myFantasy = someClosure(2).howDoIGetThis
assert myFantasy == 6
这是可能的吗?不,无法获取变量,因为闭包只返回一个结果,所以somclosure2.howdoGetThis无法工作,并且在运行闭包实例后无法获取该实例的句柄 我能想到的最好方法是从闭包返回多个值,如下所示:
def someClosure = {Number input->
def howDoIGetThis = input + 4
[ 2 * input, howDoIGetThis ]
}
def (normalWay, myFantasy) = someClosure(2)
assert normalWay == 4
assert myFantasy == 6
您可以将状态存储在闭包的所有者或委托中
def howDoIGetThis
def someClosure = {Number input ->
howDoIGetThis = input + 4
return input * 2
}
def normalWay = someClosure(2)
assert normalWay == 4
someClosure(2)
def myFantasy = howDoIGetThis
assert myFantasy == 6
如果要控制状态进入的对象,可以重写闭包的委托。例如:
def closureState = [:]
def someClosure = {Number input ->
delegate.howDoIGetThis = input + 4
return input * 2
}
someClosure.delegate = closureState
def normalWay = someClosure(2)
assert normalWay == 4
someClosure(2)
def myFantasy = closureState.howDoIGetThis
assert myFantasy == 6
+1个不错的选择:-虽然有点副作用,但我喜欢-超级棒。。。副作用是当您定义normalWay=someClosure2时,在应答范围内定义howdogethis的任何内容都将设置为6或其他任何内容吗?在第二个例子中