Mark Menard blogged about a hidden gem in Groovy which might be useful when you use closures a lot: Binding properties to a closure after the closure was created.
Remember, it’s simple to bind properties to a closure when those properties exist before the closure is created: Just define them. But how could you create a library of closures for user to consume?
def c = { println a // a isn't know here } def a = "Hello" def binding = new Binding () binding.setVariable ("a", a) c.setBinding (binding) c.call()
As you can see, the property a isn’t known at the time the closure is defined. The binding allows to “inject” it later.
Groovy!