Closure Delegate using Groovy “with” Method and decorating code with multiple assignments

23 / Jul / 2015 by Tarun Pareek 0 comments

Groovy is an expressive language, that is what we are going to talk about making the usage of “with” method for specifying closure delegate and making our code more succinct (brief and clearly expressed).

In my recent project, I was writing a code to resolve tenant and setting some properties to object tenant.

resolver.tenant.subdomain = "india"
resolver.tenant.username = "Tarun" = "ttn"
resolver.tenant.resource = "user"

As there are many other properties it becomes cumbersome to write resolver.tenant as a lot of properties are being set on same object tenant. As we are repeating ourselves here and properties that are associated with tenant are overshadowed by resolver.tenant.

Here tenant is our object of ResolvedTenant class.

One of the way to make it more expressive is to use closure delegate :

def tenantClosure = {

tenantClosure.delegate = resolver.tenant


But using groovy “with” method will make code much easier to understand and write, making code more compact and readable. Let’s try it out.

resolver.tenant.with {
    subdomain = "india"
    username = "Tarun"
    group = "ttn"
    resource = "user"

Here object on which “with” is being called, is a object used to define closure delegate and all the properties within that object can be accessed directly within “with” closure. We can also invoke methods bind to object in “with” closure. As you can see we have saved ourselves declaring closure delegate and calling closure using “with” Method.

Decorating or making it more groovier using multiple assignments and “with”, we can reduce entire block to single line :

resolver.tenant.with {
  (subdomain, username, group, resource) = ["india","Tarun","ttn","user"]

For further reference, take a look over multiple assignments blog : Multiple Variable Assignment by Ankur Tripathi

For those who are not much familiar with goodness of multiple assignments and “with” Method in groovy.

Hope it helps 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *