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


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

3 6 9 12 15 18 

2. String Literals vs String Expressions

In Groovy, you can define a String in a few ways: with a single quote or double quote. But what is the difference? The single quote is a literal and the second is an expression. A literal takes what is inside of it and accepts it literally, never evaluating it. A double qoute is an expression, and whatever is inside is evaluated.

A literal takes exactly what is inside.
def myName = "Nirav"
print 'This is my name: ${myName}'

This is my name: ${myName}

A literal can come in handy if you want to avoid using escape characters to clutter up code.

An expression evaluates a variable.
def myName = "Nirav"
print "This is my name: ${myName}"

This is my name: Nirav

3. String Convenience Methods

There are some handy methods on Strings in Groovy.

A multi-line string can give clarity to your code. I find it handy when describing an sql expression.
""" select * 
    from person 
    where name = 'Bob' """

Use overloaded methods in String to manipulate the string.
def sentence = "I am tired of all the damn crap in politics"
sentence -= "damn crap" // remove the potty mouth
sentence += ", but I still like Obama"
println sentence

I am tired of all the  in politics, but I still like Obama

4. Groovy Truth

Groovy truth can provide problems if you are not aware of it. However, you can use it to your advantage to reduce code. Essentially, groovy truth evaluates anything with a value populated to 'true', while evaluating anything empty or null to 'false'.

if (value) {
    println "${value} evaluated to true"
else {
    println "${value} evaluated to false"

0 evaluated to false
1 evaluated to true
[] evaluated to false
null evaluated to false
 evaluated to false
hello evaluated to true


  1. Hi! Nice post.

    I know your first example is about iterating but it could be simplified.

    def sum = (10..15).inject(0) { s, i -> s += i }
    println sum //75


    def sum = (10..15).sum()
    println sum //75

    With groovy, a lot of times you find that you really don't need to iterate and change a variable.

  2. Thanks that's a good suggestion. Yes upto is one of many ways to iterate. can you think of any unique ways to use upto?

  3. Hi Nirav, here is a shorter truthTester, although not as clear for novices.

    def groovyTruthTester = { value ->
    println "${value} evaluated to ${value as boolean}"