O'Reilly logo

Programming Groovy 2 by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required