The other day I was talking to some coworkers about a groovy method that I had refactored. It was one that I had pulled the guts out because I needed two forms of the same data. So I added getDaySizeList which contains most of the logic, but I still needed to get a rollup sum from getDuration for another part of the application.
I knew groovy collections supported an “each” function that takes a closure. Groovy syntax allows for omission of parentheses when there is at least one argument, so it can look like this:
myCollection.each{ closure } not myCollection.each({ closure })
it would also allow you do things like:
myCollection.add object (look no parens!)
which creeps me out right now, so I’m not going to think about it.
I digress… Here is my method, that I thought was a short implementation:
int getDuration(){
int hours = 0;
getDaySizeList().each{dayHourMap -> hours += dayHourMap.hours}
return hours
}
I was excited, no visible loop, just something to do “each” for the members of the collection, drilling down into the hours property of the map in each collection item, summing them into a waiting “hours” int, then returning it. Slick.
Barney then replied that I should have (duh) used the sum closure-taking builtin in groovy… which turns the above method into this:
int getDuration(){
return getDaySizeList().sum{it.hours}
}
“it” is the default single argument to the closure. You can see I only kept the end of the closure, to the right of the former +=.
Magic.