简体   繁体   English

Groovy:如何获得“私有”的价值? 封闭变量

[英]Groovy: how to get the value of a ?private? closure variable

I have a closure thats working great, but sometimes I would like to get the final value of a temporary variable I define in the closure. 我的闭包效果很好,但是有时我想获得在闭包中定义的临时变量的最终值。 Example: 例:

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

Is this somehow possible? 这可能吗?

You can store the state in the closure's owner or delegate. 您可以将状态存储在闭包的所有者或委托中。

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

If you want to control what object the state goes into, you can override the closure's delegate. 如果要控制状态进入的对象,则可以覆盖闭包的委托。 For example: 例如:

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

No, there's no way of getting the variable, as the closure just returns a single result (so somclosure(2).howDoIGetThis can't work), and there's no way to get a handle on the closure instance after it has been run... 不,没有办法获取变量,因为闭包仅返回一个结果(因此somclosure(2).howDoIGetThis不能工作),并且在闭包实例运行后也无法获取句柄。 ..

The best I can think of, is to return multiple values from the Closure like so: 我能想到的最好的办法是从Closure返回多个值,如下所示:

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

def (normalWay, myFantasy) = someClosure(2)

assert normalWay == 4
assert myFantasy == 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM