Reputation: 11
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
Reputation: 9885
You can use curry().
def x = 'foo'
def closure = { it }.curry(x)
x = 'bar'
assert closure() == 'foo'
Upvotes: 0
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