Closures and Bindings in Groovy

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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: