Tuesday, October 16, 2012

SpringOne 2GX - What's New in Groovy 2.0

Presenter: Guillaume Laforge
8:30am 10/16

Groovy 1.8 stuff:

Now bundle the GPars library in the groovy distribution. This library is for implementing various kinds of parallel processing. You can use GPars from pure Java, as well.

Enhancements to syntax for method chanining (less dots and parentheses).

Can use closures in @annotations

Memoization of closures

Built-in JSON support

e.g.,
def payload = new URL("http://github.../json/commits/...").text
def slurper = new JsonSlurper()
def doc = slurper.parseText(payload)
doc.commits.message.each { println it}
or to create JSON:
import groovy.json.*

def json = new JsonBuilder()
json.person {
  name "Guillaume"
  age 35
  pets "Isabella", "Sage", "Tigger"
}

Lots of new annotations

@Log, @Log4j, @Commons, @Slf4j - logging injection
@ThreadInterrupt import goovy.transform.ThreadInterrupt - annotation can be added at the beginning of any block or closure
@InheritConstructors - annotation added to derived class that causes all of its parent's constructors to be inherited (useful for exception classes)

Groovy 2.0

Groovy 2.0.0 released in June. Currently at 2.0.5.
Three main themes: modularity, Java 7 alignment, static type checking and compilation (big!)

Modularity

groovy-all.jar has been decomposed into smaller modules (although groovy-all.jar is still available)

Add ability for user to define extension methods (methods available to ordinary Java classes).


package foo
class StringExtension {
  static introduces(String self, String name) {
    "Hi ${name}, I'm ${self}"
  }
}

"Guillaume".introduces("Cederic")



[Need to add descriptor to META-INF/services/org.codehaus.groovy.runtime.ExtensionModule]

Java 7 alignment

  • binary literals (0b010101)
  •  can use _ in numeric literals (1_000_000, 999_99_9999, 9999_9999_9999_9999)
  • multicatch try { ... } catch ( Exception1 | Exception2 e ) { }
  • InvokeDynamic - better runtime performance (requires compiler flag to enable compiling against JDK 7)
  • works with java 1.5, 1.6, 1.7 

Static Type Checking

Goal: make the Groovy compiler "grumpy":
  • complain about method/variable name typos
  • complain about assignments of incorrect types
  • infer types of variables
  • GDK methods are type-checked by default
Don't always need dynamic features (e.g., dynamic methods)

import groovy.transform.TypeChecked
@TypeChecked (annotation can be made on class or method)

Static Compilation

Use @CompileStatic annotation on class to request.

Benefits:
  • can generate same byte code as javac (big performance gain!)
Drawbacks:
  • lose dynamic language features (e.g., builders, metaclass changes, categories)

0 Comments:

Post a Comment

<< Home