Groovy Closures

I been writing some Groovy scripts recently. For the most part I have been writing small function that iterate over some list of maps. One great feature of Groovy is closures. Yeah, I know Ruby also has closures but for the following examples I will stick to Groovy. The following is a typical example of iterating through each element in a list using closures in Groovy:

[1, 2, 3].each { item ->
   println item;
}

In the above example the square brackets defines a literal list while the closure is composed within the curly braces. For each element in the list the code inside the closure will be executed. You could have said the same thing by using a for in loop as in the following:

for(item in [1, 2, 3]) {
   println item;
}

Think of closures akin to lambda or functor functions. Closures are useful because they are anonymous code blocks that can treated as objects. Here is how you create a closure object that prints the square of a numeric.

def prsq = { println it * it};
[1, 2, 3, 4].each prsq;

The variable prsq is an instance of Closure and you can treat it as any object and pass it to methods, such as each, that expects a closure as a parameter. Notice that the variable it is defined for you within the body of the closure. You can also invoke a closure like a method in the following fashion:

prsq(10);

Here is one last example for you to try out.

def greetings = {"Hello, ${it}"}
println greetings("World");

Technorati Tags: , , , ,


Leave a Reply