empath
empath

Reputation: 11

Is it possible reference the value of a variable when building a closure in groovy, rather than the variable itself?

I understand why

x = 'foo'
closure={print x}
x = 'bar'
closure() 

will return 'bar', because the variable in the closure will always reference the current value of the variable. But what i'd like to do is dynamically build a closure {print 'foo'} so that when I call the closure, it always prints the same thing, based on whatever x happened to be at the time I built the closure. Is that possible?

Upvotes: 0

Views: 87

Answers (2)

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

You can use curry().

def x = 'foo'
def closure = { it }.curry(x)

x = 'bar'
assert closure() == 'foo'

Upvotes: 0

tim_yates
tim_yates

Reputation: 171194

You can add a level of indirection with a method, so the closure closes over the method parameter instead of the external variable

def close(x) {
    { -> println x }
}

x = 1
closure = close(x)
x = 2
closure()

Or, you can do it with the (arguably less readable) double closure call:

x = 1
closure = { x -> { -> println x } }(x)
x = 2
closure()

Upvotes: 1

Related Questions