July 2013
Intermediate to advanced
370 pages
8h 27m
English
We covered how to create a closure just in time, at the point of defining arguments in a method call. We can also assign them to variables and reuse them, as we’ll do here.
In the following example,
totalSelectValues
accepts a closure to help decide the set of values used in a computation:
| UsingClosures/Strategy.groovy | |
| | def totalSelectValues(n, closure) { |
| | total = 0 |
| | for(i in 1..n) { |
| | if (closure(i)) { total += i } |
| | } |
| | total |
| | } |
| | print "Total of even numbers from 1 to 10 is " |
| | println totalSelectValues(10) { it % 2 == 0 } |
| | |
| | def isOdd = { it % 2 != 0} |
| | print "Total of odd numbers from 1 to 10 is " |
| | println totalSelectValues(10, isOdd) |
The method
totalSelectValues
iterates from 1 to n. For each ...
Read now
Unlock full access