Jim Driscoll's Blog

Notes on Technology and the Web

A quick introduction to the Groovy language (part 1)

leave a comment »

Before I start talking about using Groovy’s capabilities to create a DSL (mostly in Java), let’s take a few minutes to go over what Groovy is.

Groovy is a general purpose scripting language which runs on the JVM, and can largely be viewed as a superset of Java.  Take the following program:

public class Hello {
    String name;
    
    public void sayHello() {
        System.out.println("Hello "+getName()+"!");
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

Is this a Groovy program or a Java program?  Yes, it is – it will compile and run in both.  This basic program is a bit wordy, and we can certainly do things more simply in Java, but this contains a number of patterns that you’d commonly see, including the use of the bean pattern, as well as the use of the main method to make the class executable via the java command line program.    When we run it, it simply prints out “Hello world!”, as is customary in these sorts of things.

To try this out in Java, you can use your favorite IDE.  You can also use an IDE to try this in Groovy, but you may just want to use the groovyConsole program, which is available as part of the GDK.  Download it now, and play along via cut and paste…

Now, as I said, Groovy is a rough superset of Java – one difference is that things are public by default.  That means we could just as easily say the following:

class Hello {

    String name;
    
    void sayHello() {
        System.out.println("Hello "+getName()+"!");
    }
    
    void setName(String name) {
        this.name = name;
    }
    
    String getName() {
        return name;
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

 

Accessors and mutators are automatically created for your class variables, so we can also shorten it by taking those out:

class Hello {

    String name;
    
    void sayHello() {
        System.out.println("Hello "+getName()+"!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

 

Now we’re getting somewhere.  In Groovy, System.out.println can be shortened to just “println” as a convenience, so you can also say:

class Hello {

    String name;
    
    void sayHello() {
        println("Hello "+getName()+"!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName("world");
        hello.sayHello();
    }
}

 

There’s also a difference in how Groovy deals with String objects – double quote strings allow for variable substitution.  There’s also single quote strings, which do not:

class Hello {

    String name;
    
    void sayHello() {
        println("Hello $name!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.setName('world');
        hello.sayHello();
    }
}

 

Groovy also allows dot notation to get and set fields of classes, just like Java.  Unlike Java, this will actually go through the getter/setter methods (which, you’ll recall, are automatically generated in our current example):

class Hello {

    String name;
    
    void sayHello() {
        println("Hello $name!");
    }
    
    static void main(String[] args) {
    
        Hello hello = new Hello();
        hello.name = 'world';
        hello.sayHello();
    }
}

 

Typing information is also optional – instead of specifying a type, you can just use the keyword def.  Use of def is mandatory for methods, but optional for parameters on those methods.  You should also use def for class and method variables.  While we’re at it, let’s take out those semicolons:  They’re optional in Groovy.

class Hello {

    def sayHello(name) {
        println("Hello $name!")
    }
    
    static def main(args) {
        Hello hello = new Hello()
        def name = 'world'
        hello.sayHello(name)
    }
}

 

OK, that’s nice, but we can get this even shorter. Because Groovy is a scripting language, there’s automatically a wrapping class (called Script, which will become very important to us later). This wrapping class means that we can get rid of our own wrapping class, as well as the main method, like so:

def sayHello(name) {
    println("Hello $name!")
}
def name = 'world'
sayHello(name)

 

That’s all for now, I’ll do a second part to this later.  But for now, if someone asks you if you know Groovy, you can now say “Sure, a bit”.

Credit for the idea behind this post goes to Guillaume Laforge – I saw him give a variation of this as an intro to his talk at JavaOne, and loved it.

About these ads

Written by Jim Driscoll

March 16, 2012 at 11:16 AM

Posted in Groovy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 411 other followers

%d bloggers like this: