Jim Driscoll's Blog

Notes on Technology and the Web

A quick introduction to the Groovy language (part 2)

leave a comment »

In my previous post, I started with a simple Java program (which also worked in Groovy), and slowly stripped out the cruft until I was left with the following Groovy script:

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

 

Now, let's add a little change to use an array.  Since Groovy is a rough superset of Java, you might be tempted to do something like:

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

String[] names = {"SintSi", "Kaitlyn", "Keira"}

for (String name : names) {
    sayHello(name)
}

 

But this won't work.  This is one place where Java syntax differs from Groovy's. To create a static array, you'd instead do:

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

String[] names = ["SintSi", "Kaitlyn", "Keira"]

for (String name : names) {
    sayHello(name)
}

 

As before, we can eliminate the type declarations:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

for (def name : names) {
    sayHello(name)
}

 

But a more Groovy way of doing the same thing would be to use the "in" keyword:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

for (name in names) {
    sayHello(name)
}

 

Note that under the hood, this code is no longer creating an array - rather, Groovy is (invisibly) creating an ArrayList.  This gives us a number of new options - for instance, sorting:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

names.sort()

for (name in names) {
    sayHello(name)
}

 

You can also add and remove entries to the list, like so:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

names += 'Jim'
names -= 'SintSi'
names.sort()

for (name in names) {
    sayHello(name)
}

 

But this still isn't the way that many Groovy coders would do it. They'd probably use the built in method each, which takes a closure as an argument.  If you aren't already familiar with closures (I knew them already from JavaScript), they're similar in many ways to method pointers.  And you might as well start learning about them, they're coming to Java (finally).  To use a closure, you define it using enclosing curly braces, and you can call it with the call method, like so:

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

def clos = {name -> sayHello(name)}
clos.call('world')

 

This will print "Hello world!".  Note that if you're trying this in groovyConsole, you'll see an additional value at the end - this is because Groovy scripts always return the last value as the return value, and groovyConsole is showing you the value of the names ArrayList.  In this example, the "name ->" preamble defines a single parameter that the closure takes.  Now let's use the closure with the each method:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

names += 'Jim'
names -= 'SintSi'
names.sort()

def clos = {name -> sayHello(name)}
names.each(clos)

 

Under the covers, names.each is iterating through the collection, and passing each value to the closure as the first parameter, just as in our previous example.  We can simplify this by creating the closure in place.  And since in Groovy, method parenthesis are optional when the method takes one or more parameters, we can say:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

names += 'Jim'
names -= 'SintSi'
names.sort()

names.each {name -> sayHello(name)}

 

Which is pretty darn readable.  One more thing:  by default, the first parameter of a closure is named "it".  So, you could instead say:

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

def names = ["SintSi", "Kaitlyn", "Keira"]

names += 'Jim'
names -= 'SintSi'
names.sort()

names.each {sayHello(it)}

 

That's it for now. If you've followed along so far, you've gotten more than enough Groovy under your belt to deal with anything you might see in my coming posts, as well as being able to say "Sure, more or less", when someone says "Do you know any Groovy?"

 

About these ads

Written by Jim Driscoll

March 17, 2012 at 7:50 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 412 other followers

%d bloggers like this: