Getting Groovy (and Grails)

Explorations in Groovy and Grails Development

The Gr8 Conference: What’s new in Groovy 1.6

with 4 comments

After Dierks presentation, Guillaume LaForge was up next, providing an overview of the features of Groovy 1.6(.3). He covered a lot of materials – much of which is contained in his recent InfoQ article.

Introducing Groovy
He started with a brief introduction to Groovy. It’s a dynamic language on the JVM, it provides a Meta Object Protocol which allows for meta-programming techniques such as intercepting method calls. It compiles down to byte code, it’s an open source Apache licensed project and has a relaxed grammar derived from Java 5 (most Java code is valid Groovy code). It borrows ideas from other dynamic languages such as Smalltalk, Pyton and Ruby, has Java 5 features out of the box (annotations, generics, static imports, enums, etc) and with a flat learning curve for Java devs and the ability to run on the Google App Engine (check out http://groovyconsole.appspot.com), it’s really quick and easy to get started with.

Groovy is fully OO (no primitives, so you can add methods to numbers and write things like 1.day just like you would in Ruby), there is a joint compiler with the capacity for resolving circular dependencies between Java and Groovy code, it supports Closures, properties (no getters/setters required), optional typing and BigDecimal arithmetic by default for floating point numbers. There are handy APIs for XML, JDBC, JMX, templating and Swing UI’s, a strong ability for writing business user readable Domain Specific Languages, syntax level “builders” and it supports easy operator overloading (if you want to write 10.meters + 20.kilometers, for example).

It supports lists “def numbers = [1,2,3,4]”, maps “def map = [FR: ‘France] , BE: ‘Belgium’]” and ranges “def allowed = 18..65”. It allows for regular expressions, and has GStrings which are interpolated strings which allow for placeholder variable replacements “Hello ${FirstName}”. Triple double-quotes also allow you to create multi-line strings without having to concatenate the strings as you would in Java.

One of the key features of Groovy is support for Closures. These are reusable and assignable code blocks (anonymous functions). So for instance, you could write:
def greet = {println “hello ${it}”}
greet(“Guillame”)

You can pass parameters to closures:
def greet = {string name -> println “Hello ${name}”}

and you can pass closures around:
def method(Closure c) { c(“Hello”)}
method(greet)

They take a bit of getting used to, but can provide a great deal of expressiveness in your code as you get the hang of how and where to use them.

One of Groovys other great features is a set of builders. For example, the following script uses a markup builder to generate HTML (it could also be used for XML):
def mkp = new MarkupBuilder()
mkp.html {
head {
title “Groovy in action”
}
body {
div(width: ‘100’) { p(class: ‘para’) {span: ‘best book ever’}}
}
}
}

Groovy 1.6
After providing a brief overview of Groovy, Guillaume then went on to introduce the key improvements in the recently released Groovy 1.6.

Firstly, it’s faster – both at runtime and at compile time. groovyc tests 3-5 times faster than the 1.5 compiler and with advanced call-site caching techniques, he’s seen 150-460% increases in performance over 1.5 (although obviously your milage will vary).

There are also syntax enhancements with support for multiple variable assignment:
def (a , b) = [1 , 2]

def lat , long
(lat , long) = geocode(‘Paris’)

(a,b) = [b,a]

If there are mismatches in the number of elements, extra elements on the left just aren’t assigned to anything. If there are less elements on the left, nulls are put into the additional values on the right hand side of the assignment operator.

With Groovy 1.6 there is also support for optional returns in if/else and try/catch blocks. So you could write:
def method() {if (true) 1 else 0}

Groovy 1.6 also provides full support for Java 5 annotations. It is the only dynamic language to provide this feature.

Compile time meta-programming
Meta-programming is the ability of a program to modify itself. Groovy 1.6 adds support for Abstract Syntax Tree (AST) transformations, which should allow us to get rid of a lot of boilerplate technical code.  Groovy supports two kinds of transformations: global transformations, and local transformations that are triggered by annotations.

Out of the box, Groovy 1.6 comes with annotations such as @Singleton, @Immutable, @Lazy, @Delegate, @Nawify, @Category and @Mixin. Each saves you from writing a bunch of boiler plate code and allows you to more clearly express the intent of your code. You can also add your own global or local ASTs. It’s a technique you want to use sparingly as it would be easy to introduce hard to track down bugs where certain combinations of annotations introduced errors when they were used together, but it’s a great technique to have and something I’m going to be playing with and writing about more on this blog.

Guillaume also reviewed a number of other enhancements that have been added to Groovy 1.6. We now have Grape – the “Groovy Advanced Packaging System” which helps you to distribute your applications without having to include dependencies. You just declare the dependencies with @Grab and it’ll get them from Maven or Ivy repositories. @Bindable makes it easier to do data binding in swing, and the swing console application can now be run as an applet, has code indent support, script drag and drop and the ability to add jars to the classpath from the IDE.

The ExpandoMetaClass DSL is another new feature that I’ll be covering in more detail on the blog, but briefly, it’s a DSL for changing the behavior of types at runtime. There is also the support for runtime mixins:
JamesBondVehicle.mixin FlyingAbility

In addition, Groovy 1.6 had JSR-223 bundled, so if you simply can’t get through the day without adding a little Python or PHP to your Groovy, it’s supported out of the box. There is also a JMX builder available (http://groovy.codehaus.org/groovy+jmxbuilder). Finally, the Groovy 1.6 JAR contains OSGi metadata and can be used in OSGi containers (http://groovy.codehaus.org/osgi+and+groovy).

With only on hour to both introduce Groovy and provide an overview of the new 1.6 features, it was a high level presentation, but it was a great introduction to the language and provided a good overview of the latest additions to the language.

Advertisements

Written by peterbell

May 20, 2009 at 5:31 pm

Posted in Conferences, gr8

4 Responses

Subscribe to comments with RSS.

  1. Thanks for the write-up Peter. This is amazing, thanks for sharing with us.

    Can you clarify:

    In addition, Groovy 1.6 had JSR-223 bundled, so if you simply can’t get through the day without adding a little Python or PHP to your Groovy, it’s supported out of the box.

    What does this mean? Can I run PHP with groovy?

    Tomas

    May 20, 2009 at 9:13 pm

  2. Hi Tomas,

    To be fair, I’m not sure, but JSR-233 is about scripting interoperability, so typically when people mention it they’re discussing being able to run other JVM scripting languages from their one. For instance, in ColdFusion there are projects that allow you to run Groovy and the Quericus PHP within ColdFusion code using the JSR-233 stuff. Not something I’ve played with as the level of integration makes it “interesting but not compelling” at least for most of my use cases.

    I’m guessing the real benefit would be if you wanted to (say) write a chunk of your code in Scala or Clojure, using the functional paradigm and then to call that from your Groovy, but as I said, I haven’t played with this yet. If you play with it and blog it, please ping me so I can share it around!

    peterbell

    May 21, 2009 at 8:28 am

  3. […] the standouts are an excellent write-up on what’s new in Groovy 1.6 and a summary of a session titled “Groovy Usage Patterns“, both by Peter Bell (the […]

  4. […] » Last year I posted a fairly comprehensive series of articles on the blog (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) summarizing the content from Gr8 in Copenhagen. This year I opted instead […]


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

%d bloggers like this: