Command Chains and Modules

Learn about command chains and modules used in Groovy.

Command chains

Groovy 1.8 added command chains, which allow for a completely fluent DSL for an even number of words.

For example, pull request on github will be executed as pull(request).on(github). Groovy 1.8 also added the following:

  • Closure annotation parameters: @Invariant({number >= 0})
  • Closure memoization: {...}.memoize()
  • Built-in JSON support - Consuming, producing, and pretty-printing
  • New AST Transformations: @Log, @Field, @AutoClone, and @AutoExternalizable, …

Modules

In Groovy 2.0, the monolithic Groovy jar was broken down into multiple jars so we can pick and choose what our project needs and keep our final project’s size down. It also added the ability to create our own modules using Extension modules.

Static type checking

Adding the @TypeChecked annotation to our class causes the compiler to enforce compile-time type-checking. It will infer types for us, so our code can still be Groovy.

  • Infers Lowest Upper Bound (LUB)
  • Gotcha’s:
    • Runtime meta-programming won’t work!
    • Explicit type needed in closure: a.collect {String it -> it.toUpperCase()}

Adding the @StaticCompile annotation to your class causes the compiler to compile your Groovy code to byte-code.

  • Type-checking: No one else can change byte-code.
  • Binary identical to compiled Java (almost).

In summary:

  • @StaticCompile: Compiles your Groovy code to byte-code.
  • @TypeChecked: Enforces compile-time type-checking.

Invoke dynamic support in Groovy

Groovy 2 added total support for Java’s invokedynamic bytecode command, greatly improving performance. However, it is not enabled by default.

To enable invokedynamic support (lovingly called “indy”), you can do the following in a Gradle build file:

tasks.withType(GroovyCompile) {
     groovyOptions.optimizationOptions.indy = true
}

Also, make sure to change your dependency to use the indy classifier:

compile "org.codehaus.groovy:groovy-all::indy"

Get hands-on with 1200+ tech skills courses.