Reputation: 4742
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?
Upvotes: 2
Views: 1239
Reputation: 66109
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
Upvotes: 3
Reputation: 171194
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
Upvotes: 2