Search code examples
groovyscopeclosuresprivate

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?


Solution

  • 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