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.

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

Start Free Trial

No credit card required