Saturday, January 13, 2007

Groovy man...

I recently posted a comment about JDK 7 in this blog. The entry was about how the proposals for JDK 7 are starting to move Java more towards a language like Groovy. My comments were along the lines of Sun needs to back more languages running on the JVM (specifically dynamically typed languages--like Groovy and Beanshell) and improving the overall quality of the core libraries.

As a result of this entry, I decided to see what Groovy was all about. The day Groovy 1.0 was released I downloaded it because I was curious. I installed it, but didn't do much more than that. When I read the aforementioned blog (which I was tipped off to on the groovy-users mailing list), it really got me more interested in Groovy.

The next thing I did was download Eclipse and the Groovy plugin. Normally I use Netbeans to do development, but I chose Eclipse this time (Netbeans is excellent for other things though). I went to work with the test script on the page that's on the plugin install page, namely:


class GTest {
static void main(args) {
def list = ["Rod", "Phil", "James", "Chris"]
def shorts = list.findAll {
it.size() < 5
}
shorts.each {
println it
}
}
}

And the first question I had was "What is it?" Secondly I'm a Java developer so Closures, while not a completely foreign concept to me, are different. I decided to experiment with it.

I ran the script and I thought "why are only the first 2 names being printed to the console?" I was dying to know what this thing was doing and how it was doing it.

The first thing I did was step through the script in the debugger without ever having the thought occur to me that you can't possibly debug a script in the JVM. I guess you can because I was able to step through and see what was going on. Unfortunately, the debugger didn't reveal anything obvious about the mysterious it.

Then I changed it to shit and then run the script. This got a different result. Instead of Rod and Phil being printed to the console, an exception was thrown. I knew immediately that although Groovy is dynamically typed, it wasn't going to take any shit. Especially any uninitialized shit.

Finally I broke down and do what I always do in situations like this. I read the documentation. That's right, I read it. And in the documentation for Closures, I finally found:
Closures may have 1...N arguments, which may be statically typed or untyped. The first parameter is available via an implicit untyped argument named it if no explicit arguments are named. If the caller does not specify any arguments, the first parameter (and, by extension, it) will be null.
The it has a meaning! Ha! Who knew??? Seriously, it (both the explanation and implementation) makes sense.

So, I'm starting. I'm hoping to find out some good stuff with all this. I'll be sure to share.

No comments: