The Convenience of Closures

Closures in Groovy totally remove verbosity in code and help create lightweight reusable pieces of code. To understand the convenience they offer, let’s contrast them with familiar traditional solutions for common tasks.

The Traditional Way

Let’s consider a simple example—assume we want to find the sum of even values from 1 to a certain number, n.

Here is the traditional approach:

UsingClosures/UsingEvenNumbers.groovy
 
def​ sum(n) {
 
total = 0
 
for​(​int​ i = 2; i <= n; i += 2) {
 
total += i
 
}
 
total
 
}
 
println ​"Sum of even numbers from 1 to 10 is ​${sum(10)}​"

In the method sum, we’re running a for loop that iterates over even numbers and sums them. Now, suppose instead of that we want to find the product ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.