InfoQ Homepage Articles What’s new in Groovy 2.0?

# What’s new in Groovy 2.0?

Leia em Português

This item in japanese

Lire ce contenu en français

The newly released Groovy 2.0 brings key static features to the language with static type checking and static compilation, adopts JDK 7 related improvements with Project Coin syntax enhancements and the support of the new "invoke dynamic" JVM instruction, and becomes more modular than before. In this article, we’re going to look into those new features in more detail.

## Static type checking

Groovy, by nature, is and will always be a dynamic language. However, Groovy is often used as a "Java scripting language", or as a "better Java" (ie. a Java with less boilerplate and more power features).

A lot of Java developers actually use and embed Groovy in their Java applications as an extension language, to author more expressive business rules, to further customize the application for different customers, etc. For such Java-oriented use cases, developers don't need all the dynamic capabilities offered by the language, and they usually expect the same kind of feedback from the Groovy compiler as the one given by javac. In particular, they want to get compilation errors (rather than runtime errors) for things like typos on variable or method names, incorrect type assignments and the like. That's why Groovy 2 features static type checking support.

## Spotting obvious typos

The static type checker is built using Groovy’s existing powerful AST (Abstract Syntax Tree) transformation mechanisms but for those not familiar with these mechanisms you can think of it as an optional compiler plugin triggered through an annotation. Being an optional feature, you are not forced to use it if you don’t need it. To trigger static type checking, just use the @TypeChecked annotation on a method or on a class to turn on checking at your desired level of granularity. Let’s see that in action with a first example:

import groovy.transform.TypeCheckedvoid someMethod() {}@TypeCheckedvoid test() {    // compilation error:    // cannot find matching method sommeeMethod()    sommeeMethod()    def name = "Marion"    // compilation error:    // the variable naaammme is undeclared    println naaammme}

We annotated the test() method with the @TypeChecked annotation, which instructs the Groovy compiler to run the static type checking for that particular method at compilation time. We’re trying to call someMethod() with some obvious typos, and to print the name variable again with another typo, and the compiler will throw two compilation errors because respectively, the method and variable are not found or declared.

## Check your assignments and return values

The static type checker also verifies that the return types and values of your assignments are coherent:

import groovy.transform.TypeChecked@TypeCheckedDate test() {    // compilation error:    // cannot assign value of Date     // to variable of type int    int object = new Date()    String[] letters = ['a', 'b', 'c']    // compilation error:    // cannot assign value of type String     // to variable of type Date    Date aDateVariable = letters[0]    // compilation error:    // cannot return value of type String     // on method returning type Date    return "today"}

In this example, the compiler will complain about the fact you cannot assign a Date in an int variable, nor can you return a String instead of a Date value specified in the method signature. The compilation error from the middle of the script is also interesting, as not only does it complain of the wrong assignment, but also because it shows type inference at play, because the type checker, of course, knows that letters[0] is of type String, because we’re dealing with an array of Strings.

## More on type inference

Since we’re mentioning type inference, let’s have a look at some other occurrences of it. We mentioned the type checker tracks the return types and values:

import groovy.transform.TypeChecked@TypeCheckedint method() {    if (true) {        // compilation error:        // cannot return value of type String        // on method returning type int        'String'    } else {        42    }}

Given a method returning a value of primitive type int, the type checker is able to also check the values returned from different constructs like if / else branches, try / catch blocks or switch / case blocks. Here, in our example, one branch of the if / else blocks tries to return a String value instead of a primitive int, and the compiler complains about it.

## Common type conversions still allowed

The static type checker, however, won’t complain for certain automatic type conversions that Groovy supports. For instance, for method signatures returning String, boolean or Class, Groovy converts return values to these types automatically:

import groovy.transform.TypeChecked@TypeCheckedboolean booleanMethod() {    "non empty strings are evaluated to true"}assert booleanMethod() == true@TypeCheckedString stringMethod() {    // StringBuilder converted to String calling toString()    new StringBuilder() << "non empty string"}assert stringMethod() instanceof String@TypeCheckedClass classMethod() {    // the java.util.List class will be returned    "java.util.List"}assert classMethod() == List

The static type checker is also clever enough to do type inference:

## Contributing a static method

For static extension methods, this is the same mechanism and convention. Let’s add a new static method to Random to get a random integer between two values, you could proceed as in this class:

package com.acmeclass MyStaticExtension {    static String between(Random selfType, int start, int end) {        new Random().nextInt(end - start + 1) + start    }}

That way, you are able to use that extension method as follows:

Random.between(3, 4)

## Extension module descriptor

Once you’ve coded your helper classes (in Groovy or even in Java) containing the extension methods, you need to create a descriptor for your module. You must create a file called org.codehaus.groovy.runtime.ExtensionModule in the META-INF/services directory of your module archive. Four essential fields can be defined, to tell the Groovy runtime about the name and version of your module, as well as to point at your helper classes for extension methods with a comma-separated list of class names. Here is what our final module descriptor looks like:

moduleName = MyExtensionmoduleVersion = 1.0extensionClasses = com.acme.MyExtensionstaticExtensionClasses = com.acme.MyStaticExtension

With this extension module descriptor on the classpath, you are now able to use those extension methods in your code, without needing an import or anything else, as those extension methods are automatically registered.

## Grabbing an extension

With the @Grab annotation in your scripts, you can fetch dependencies from Maven repositories like Maven Central. With the addition of the @GrabResolver annotation, you can specify your own location for your dependencies as well. If you are "grabbing" an extension module dependency through this mechanism, the extension method will also be installed automatically. Ideally, for consistency, your module name and version should be coherent with the artifact id and version of your artifact.

## Summary

Groovy is very popular among Java developers and offers them a mature platform and ecosystem for their application needs. But without resting still, the Groovy development team continues to further improve the language and its APIs to help its users increase their productivity on the Java platform.

Groovy 2.0 responds to three key themes:

• More performance: with the support of JDK 7 Invoke Dynamic to speed up Groovy for those lucky to have JDK 7 already in production, but also with static compilation for JDK 5 and beyond for everyone, and particularly those ready to abandon some aspects of dynamicity to shield themselves from the reach of "monkey patching" and to gain the same speed as Java.
• More Java friendliness: with the support of the Java 7 Project Coin enhancements to keep Groovy and Java as close syntax cousins as ever, and with the static type checker to have the same level of feedback and type safety as provided by the javac compiler for developers using Groovy as a Java scripting language
• More modularity: with a new level of modularity, Groovy opens the doors for smaller deliverables, for example for integration in mobile applications on Android, and allowing the Groovy APIs to grow and evolve with newer versions and newer extension modules, as well as allowing users to contribute extension methods to existing types.

As Head of Groovy Development for SpringSource, a division of VMware, Guillaume Laforge is the official Groovy Project Manager, leading the Groovy dynamic language project at Codehaus.

He initiated the creation of the Grails web application framework, and founded the Gaelyk project, a lightweight toolkit for developing applications in Groovy for Google App Engine. He is also a frequent conference speaker presenting Groovy, Grails, Gaelyk, Domain-Specific Languages at JavaOne, GR8Conf, SpringOne2GX, QCon, and Devoxx, among others.

Guillaume is also one of the founding members of the French Java/OSS/IT podcast LesCastCodeurs.

Style

## Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

• ##### Ready for the real breakthrough

by Ivo Houbrechts /

• ##### Re: Ready for the real breakthrough

by Alex Hugh /

• ##### Looks good

by John Dodo /

• ##### Re: Looks good

by Guillaume Laforge /

• ##### Congratulations

by Daniel Serodio /

• ##### JDK 7u8?

by Ashwin Jayaprakash /

• ##### Re: JDK 7u8?

by Guillaume Laforge /

• ##### Static compilation by default

by Stefan Undorf /

• ##### Re: Static compilation by default

by Guillaume Laforge /

• ##### Re: Static compilation by default

by James Gordon /

• ##### Re: Static compilation by default

by James Gordon /

• ##### Re: Static compilation by default

by Guillaume Laforge /

• ##### Re: Static compilation by default

by Guillaume Laforge /

• ##### Re: Static compilation by default

by James Gordon /

• ##### Re: Static compilation by default

by Alex Hugh /

• ##### @CompileStatic and Android?

by Michel Salim /

• ##### Re: @CompileStatic and Android?

by Guillaume Laforge /

• ##### Re: @CompileStatic and Android?

by Michel Salim /

• ##### Re: @CompileStatic and Android?

by Guillaume Laforge /

• ##### Great.

by Chris Gaudreau /

• ##### Re: Great.

by Alex Hugh /

• ##### Re: Great.

by Guillaume Laforge /

• ##### Re: Great.

by Alex Hugh /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### scala or groovy for creating class from script file at run time

by Veerbhan Tahlani /

• ##### Ready for the real breakthrough

Your message is awaiting moderation. Thank you for participating in the discussion.

A lot of traditional Java developers are reluctant towards Groovy because of its dynamic nature.
The (optional) static type checking offers the best of both worlds and hopefully persuades these Java developers to have a second look at Groovy.

Nice job guys!

Houbie

• ##### Looks good

by John Dodo /

Your message is awaiting moderation. Thank you for participating in the discussion.

As a Java developer, I may try Groovy with those new features, good job!

The only thing I'm not sure to like, is the "Common type conversions still allowed" part. If my method is annotated with @TypeChecked and its return type is "boolean", I want a compilation error if I try to return a String!!

Will there be a Grails version using Groovy 2.0 soon?

• ##### Congratulations

Your message is awaiting moderation. Thank you for participating in the discussion.

Congrats on the release, Groovy 2.0 really deserves the "2.0" moniker.

• ##### JDK 7u8?

Your message is awaiting moderation. Thank you for participating in the discussion.

Keep up the good work!

You said "upcoming JDK 7 updates (in particular update 8) should already contain such improvements..". As of today 7u3 is available. How do you know it'll be in update 8? That seems pretty far away.

• ##### Re: JDK 7u8?

Your message is awaiting moderation. Thank you for participating in the discussion.

I've heard some of the newer optimizations for update 6 were postponed to update 8, although I can't find a link handy to give you more details.

• ##### Re: Looks good

Your message is awaiting moderation. Thank you for participating in the discussion.

We made the type checker compliant with the common Groovy idioms, to avoid surprising our big and wide user base, so there may be a few places like the common type conversion that might be a little different than what you' expect in a static language like Java.

As for Grails, the integration of Groovy 2.0 should be in the Grails 2.2 release.

• ##### Static compilation by default

Your message is awaiting moderation. Thank you for participating in the discussion.

Congrats for this release. Is there a switch to turn on static compilation by default for the whole application and just request dynamic features where it is needed?
If Groovy really performs Java-alike now I will come back from Scala.

• ##### Re: Static compilation by default

Your message is awaiting moderation. Thank you for participating in the discussion.

Currently (ie. in 2.0) you can only put @CompileStatic explicitly at the class or method level.
At put at the class level, you can use @CompileStatic(SKIP) to the methods you want to stay dynamic (for example when using a builder).
We're investigating how to turn on type checking or static compilation more globally for 2.1.
So for now, you'll have to annotate your classes with @CompileStatic, but stay tuned ;-)

• ##### Re: Static compilation by default

by James Gordon /

Your message is awaiting moderation. Thank you for participating in the discussion.

> At put at the class level, you can use @CompileStatic(SKIP) to the methods you want to stay dynamic (for example when using a builder).

@CompileStatic(SKIP) on a method does not seem work for me in a @CompileStatic class.
With the SKIP, it compiles the code fine, but complains with a NoSuchMethodError at runtime.
TypeChecked(SKIP) works in a @TypeChecked class though
I hope I am not missing something obvious here. Here is the test code.

import groovy.transform.CompileStatic
import static groovy.transform.TypeCheckingMode.SKIP;

@CompileStatic
class GMain {

@CompileStatic(SKIP)
def test() {
def p = ['name': 'John Doe']
println p.name
}

static main(args) {
new GMain().test()
}

}

> We're investigating how to turn on type checking or static compilation more globally for 2.1.

Great. I vote for this too. Groovy++ has package level annotations.

• ##### Re: Static compilation by default

by James Gordon /

Your message is awaiting moderation. Thank you for participating in the discussion.

I should add that I am using the compiler that is bundled with the latest Eclipse plugin, rather than the standalone binary release, if that matters
dist.codehaus.org/groovy/distributions/greclips...
with the compiler is set to 2.0.0 by default.

• ##### @CompileStatic and Android?

by Michel Salim /

Your message is awaiting moderation. Thank you for participating in the discussion.

If all the classes are annotated with @CompileStatic, would it be possible to use Groovy 2.0 to develop Android applications -- either using a single project with both Groovy and Android nature, or by having a Groovy project producing a Java JAR that is then used as a dependency for the Android project?

It'd really make Android development much more pleasant, to have closures and type inferencing - FWIU only the dynamic code generation is a deal-breaker up to now.

• ##### Re: @CompileStatic and Android?

Your message is awaiting moderation. Thank you for participating in the discussion.

It's also one of the reasons why we wanted to modularize Groovy 2.0 and to allow static type checking and compilation: to be able to make Groovy run smoother on other platforms such as Android!

There's an experimental project called DiscoBot that ran with Groovy 1.7, in a pure dynamic fashion though, and that was running on Android, but it's not really been kept up-to-date. But trying Groovy 2.0 on Android is definitely something we'd like to investigate!

Or even, if you're interested, perhaps you could help us work on that?

• ##### Re: Static compilation by default

Your message is awaiting moderation. Thank you for participating in the discussion.

James, it's actually a bug, it should work.
What currently works is if you annotate each and every method with @CompileStatic, and then say skip for the one you don't want statically compiled. So this is a workaround for now, but that problem will definitely be fixed in 2.0.1.
Thanks for bringing that to my attention!

• ##### Re: Static compilation by default

Your message is awaiting moderation. Thank you for participating in the discussion.

We're tracking this problem in this JIRA issue:
jira.codehaus.org/browse/GROOVY-5564

• ##### Re: @CompileStatic and Android?

by Michel Salim /

Your message is awaiting moderation. Thank you for participating in the discussion.

I'm certainly interested - how best should we discuss this? Mailing list / issue tracker / etc. ..

• ##### Re: @CompileStatic and Android?

Your message is awaiting moderation. Thank you for participating in the discussion.

• ##### Re: Static compilation by default

by James Gordon /

Your message is awaiting moderation. Thank you for participating in the discussion.

• ##### Re: Ready for the real breakthrough

by Alex Hugh /

Your message is awaiting moderation. Thank you for participating in the discussion.

Really? I still don't get any good points in learning Groovy 2.0 despite static type checking.

• ##### Re: Static compilation by default

by Alex Hugh /

Your message is awaiting moderation. Thank you for participating in the discussion.

Hopefully too. There are a few gotcha in groovy code with static type checking. Not perfect and lack of some features that Scala has.

I won't feel safe using Groovy at this moment except may consider when version 3 is out. Till then, I would stay on Scala, by then, will be a mature language.

• ##### Great.

Your message is awaiting moderation. Thank you for participating in the discussion.

I'm really glad you guys added the static compilation feature. I'll be creating a high-volume website in a month or so and the fact that Groovy was dynamic kinda kept me away from it, despite its great syntax, etc.

Just bought Groovy in Action and Definitive Guide to Grails. Hint: you guys should write a more up-to-date book sometime. :)

• ##### Re: Great.

by Alex Hugh /

Your message is awaiting moderation. Thank you for participating in the discussion.

Ahem, intend to create high-volume website and still reading the book? Action speak louder than word or anyone can anyhow claim otherwise. Prove it and we shall see the result.

• ##### Re: Great.

Your message is awaiting moderation. Thank you for participating in the discussion.

There are already high-volume site in the wild that are actually using Groovy technology, such as all the web portals of Sky.com, for example.
And it's not even using any static feature at all, just plain dynamic Groovy.

• ##### Re: Great.

by Alex Hugh /

Your message is awaiting moderation. Thank you for participating in the discussion.

Guillaume Laforge, I was referring to Chris Gaudreau's comment, not any organization. See it?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

• ##### scala or groovy for creating class from script file at run time

Your message is awaiting moderation. Thank you for participating in the discussion.

I am trying to solve a problem where I have to keep script part in flat file and at run time create class. I can do it using groovy and scala, but not sure which i should use. I find simplicity in groovy code where as i have to do lots of type conversion in scala scripting. can you please suggest which one should i use? is groovy compatible with java8?

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
Country/Zone:
State/Province/Region:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.