X-Mas Musings #21 – Groovy 3 and 2.6

December is for many people a period of reflection or thought. So I decided to reflect upon last year’s things and thoughts — each day until Christmas. This is day 21.

ted-vinke-x-mas-musings-banner-three

Earlier this year, a beautiful announcement was made by Groovy developer Daniel Sun:

Apache Groovy 3 is on its way and includes the new “Parrot” parser — which finally allows proper Java 8 syntax in Groovy code.

You can read all the new features on danielsun1106/groovy-parser and Sergio gave us already a nice preview to read.

In a Groovy 2.x I simply could not just write:

import java.util.stream.*

def words = ['the', 'quick', 'groovy', 'parser']
words.stream()
    .filter(w -> w.length() > 5)
    .map(String::toUpperCase)
    .collect()

I would get

1 compilation error:

unexpected token: -> at line: 5, column: 15

The current parser basically does not understand the lambda expression at line 5.

In these cases, I always had to write the lambdas as closures, which would work since they can be converted into interfaces or single-abstract method (SAM) types. Most of the lamda expressions are build on a Java 8 functional interface, which is a SAM — and Groovy just does automatic closure coercion for us.

In other words, I had to write it like this:

def words = ['the', 'quick', 'groovy', 'parser']
words.stream()
    .filter { w -> w.length() > 5 }
    .map { w -> w.toUpperCase() }
    .collect()

Clooooosures.

I love Groovy, and I love to write short examples in them, but non-Groovy collegues didn’t always understand why all the closures and why I didn’t use Java 8 constructs (such as method references) where applicable.

But the wait will be over!

Already in the GroovyConsole I can write:

def words = ['the', 'quick', 'groovy', 'parser']
words.stream()
    .filter(w -> w.length() == 6)
    .map(String::toUpperCase)
    .collect()

Woohoo! Notice the lambda expression ((w -> w.length() == 6)) and method expression (String::toUpperCase)!

With 3.0, better “copy ‘n paste” compatibility (see answer Guillaume Laforge) is achieved with Java — which is a great win!

The parrot features (which also include Elvis assigments, identity operators and safe indexes) will also be backported to Groovy 2.6 which targets JDK 7 — but hey, who’s still using that one? We’re heading to Java 9 🙂

2018 is going to be a great Groovy year!