简体   繁体   中英

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...

The best I can think of, is to return multiple values from the Closure like so:

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

def (normalWay, myFantasy) = someClosure(2)

assert normalWay == 4
assert myFantasy == 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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