Groovy:如何获得私有的价值?闭包变量

时间:2012-02-28 08:43:56

标签: 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 == 6

这有可能吗?

2 个答案:

答案 0 :(得分:3)

您可以将状态存储在闭包的所有者或委托中。

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 :(得分:2)

不,没有办法获取变量,因为闭包只返回一个结果(因此somclosure(2).howDoIGetThis无法工作),而且无法获取在关闭实例运行后的句柄...

我能想到的最好的方法是从Closure中返回多个值,如下所示:

def someClosure = {Number input->
  def howDoIGetThis = input + 4
  [ 2 * input, howDoIGetThis ]
}

def (normalWay, myFantasy) = someClosure(2)

assert normalWay == 4
assert myFantasy == 6