Analytics

Wednesday, September 21, 2011

4 Groovy Tips You May Not Know

I have been programming in Groovy full time for almost two years now, and I feel quite comfortable with it. In fact, the language's idioms, shortcuts, and syntax has become part of my daily programming thinking. This is fantastic as it has opened my mind to unique programming elegance and artistry, but unfortunately on the flip-side it has cause me to cringe when looking at traditional Java code. This speaks to the efficiency and conciseness of Groovy.

Recently I decided that even though I am adequetely familiar with the language, I wanted to read Programming In Groovy by Venkat Subramanium. I was pleasantly surprised that I learned some useful tips. Below are some tips that I learned:

1. Variant Looping Mechanisms

In addition to the traditional looping constructs, such as "for (i in iterm)" or range (0..5), Groovy provides alternate ways to loop.

Use the upto function to operate on a range of values:
def sum = 0
10.upto(15) {
  sum += it
}
println sum

result:
75


Use the step function to skip values:
3.step(20, 3) {
  print "$it "
}

result:
3 6 9 12 15 18