Chris Umbel

Groovy: Dynamic Language for the JVM... Groovy!

I'm continuously encouraged by the influence dynamic languages such as Ruby and Python have had on mainstream runtimes like the CLR and JVM. Direct ports like JRuby, Jython to the JVM and IronRuby and IronPython to the CLR are truly exciting. More exciting still are languages like Boo that are built from the ground up for mainstream runtimes.

I've finally had the chance to fool around with a language I've been dying to dig in to that was built specifically for the JVM: Groovy.

Groovy is an agile, dynamically-typed, well supported language that is perhaps most famous as the basis for Groovy on Grails, a rails-like web development framework.


As I typically do I'll show you a quick twitter status example to get your feet wet. Consider the following class written in Groovy:

import javax.xml.xpath.*
import javax.xml.parsers.*

class TwitterUser {
    /*  definition of UserName property.  public accessors and mutators
        are automatically created. */
    def UserName

    /* constructor definition */
    def TwitterUser(userName) {
        this.UserName = userName

    /* public method to query twitter for the users status */
    def getStatus()
        /* pretty much just java code sans the types and semicolons */
        def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        def document = builder.parse("${UserName}.xml")
        def xpath = XPathFactory.newInstance().newXPath()
        return xpath.evaluate( '/user/status/text', document,

This Groovy class can now be consumed by Java very easily:

public class Main {
    public static void main(String[] args) {
        TwitterUser status = new TwitterUser("chrisumbel");
        /* see the accessor we didn't create? */


That's all fine and dandy, but it's practically Java. Consider the following ruby-like block which defines a list and iterates it:

[2.5, "yo", 5].each() {
    /* "it" is the current item */
    println it

Ranges are also supported:

(0..3).each { i ->
    println i

Ruby/Python-ish indexing as well:

def list = [2, 4, 6, 8]
println list[1..2]

which produces:

[4, 6]


def words = "Hack off a word"
println words[0..-6]

resulting in:

Hack off a

Nice maps too:

def map = ["name" : "Chris Umbel", "age" : 30]
println map["age"]

Real Life

Considering it fits right into NetBeans Groovy is an incredibly accessible language. Having a first class IDE never hurts. The fact that groovy classes can sit in the same project with Java classes removes pretty much all barriers (and excuses). The nature of the runtime and the tooling proves that Groovy is ready for prime time.

Fri Oct 23 2009 11:39:00 GMT+0000 (UTC)

Follow Chris
RSS Feed