Closures and Bindings in Groovy

30. December, 2011

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!


New Years Resolution: Stop being so agreeable!

30. December, 2011

How quick are you to say “sure, we can do that”?

Here are a couple of reasons to reconsider your attitude: Stop being so agreeable! by Erick Erickson.


%d bloggers like this: