Groovy Programming Language

March 3, 2007 - 4 minute read -

Welcome to the disco era...wait, wrong Groovy. Groovy the programming language is dynamic programming language that runs on the Java Virtual Machine. At a first glance it looks a lot like Ruby, but it's built from the ground up to leverage the JVM. This offers a lot of power as a transitional language. It allows you to leverage an existing investment in Java code while transitioning to a powerful, dynamic language.

Java and Groovy - Happy Together

One of the most interesting things about Groovy is that almost all standard Java code is valid Groovy code.

The quintessential example:

public class Hello
{
  public static void main(String[] args)
  {
    System.out.println("Hello");
  }
}

Is that Java code or Groovy code? In fact it's both. So what's the big deal?

Well, in Groovy you can write the same thing like:

println("Hello")

To steal Venkat Subramaniam's joke: If you get paid by lines of code, this is a terrible thing.

Easier Construction

One of the other cool things with Groovy is that you can set named properties in the constructor. Conceptually setting a bunch of properties after you construct a class is often the same thing as setting those properties in a constructor. This makes code quite a bit cleaner looking. It also means the class writer does not need to predict all the combinations of the properties you might want use to initialize an object.

car = new Car(make: "VW", model: "GTI", year: 2001)

Easier Collections

Of course they also add some interesting things to handle collections as well.
lst = [1, 2, 4, 6, 8, 12] // create java.util.ArrayList
println lst[-1]               // 12
println lst[1..3]            // [2, 4, 6]
println list[-1..-2]         // [12, 8]

Easier Code Reuse

One of the biggest things that Groovy offers, which is the baby of the new scripting languages (and the baby of a bunch of old languages), is closures. Closures are blocks of code that can be passed around and executed sharing the context of where they are called from and where they are executed.

This code separates the concept of iterating from what you want to do with the elements that are iterated over. This makes for great reusability.

public iterate(count, closure)
{
    for (i in 0..count)
        closure(i)
}
iterate(5) { println it }
val = 0
iterate(5) { val += it }

Of course this kind of thing is built into the existing collections as well.

myNums = [1, 3, 5, 7, 9, 13]
myNums.each { curNum -> println curNum }

Dynamic Messaging

Unlike languages like Java or C#, Groovy gives you the ability to respond to method calls in a dynamic way. You do not have to have all of the methods defined up front, but can rather respond to them at runtime.

baseball = ['Milwaukee' : 'Brewers', 'Chicago' : 'White Sox']
println baseball.Milwaukee        // Brewers
println baseball.'Chicago'          // White Sox

In the case of the HashMap it interprets the new "method call" as your way of asking for the value from the Hash. Of course there are many other ways that you can use this as well. You can dynamically respond to methods on any class.

class Thing
{
    def invokeMethod(String name, args)
    {
        println "I'm #{name}ing!"
    }
}

Of course this is a silly example, but it's utilized to great effect in the XML Builder.

baseball = ['Milwaukee' : 'Brewers', 'Chicago' : 'White Sox']
bldr = new groovy.xml.MarkupBuilder()
xml = bldr.teams {
    baseball.each { key, value ->
        team(city : key) {
            name (value)
        }
    }
}

Gives you:

<teams>
  <team city='Milwaukee'>
    <name>Brewers</name>
  </team>
  <team city='Chicago'>
    <name>White Sox</name>
  </team>
</teams>

Isn't that a nice way to write XML?

Conclusion

I hope that gives you a taste of Groovy. It could be a very interesting language for some problems especially if you are already a Java shop looking for some more dynamic language features. That way you don't have to abandon everything you've done in the past. Instead you can start a slow migration or a bit of exploration utilizing the older code.