Groovy elegance

by Matthijs Bierman  on July 3, 2017

If you are here, it most likely means that you are interested in seeing some of the cool features of Groovy as opposed to the Java counterparts.

When Groovy and Grails first became popular, we were still on Java 1.7, so no closures etc. If you are already adept at Java 1.8, most of the interesting things we explain here will not be completely new to you.
 

Collection literals

Lists

In Java it is relatively hard to create a list:

import java.util.List;
import java.util.Arrays;


List<Integer> list = Arrays.asList(1,2,3,4);
System.out.println(list);

Compare this with the elegant Groovy solution with a list literal, and the built-in println.

def list = [1,2,3,4]
println list

 

Maps

Using maps is even more cumbersome:

Map<String,String> map = new HashMap<>;
map.put('key1', 'value1');
map.put('key2', 'value2');

Groovy has a literal syntax, allowing you to do:

 def map = [key1:'value1', key2:'value2']

 

Closures

A closure is similar to a method that can be passed around as a reference, or an argument to a method. Many methods in the GDK use closures too, especially when it comes to collections. A few examples are:
 

Iterate

def list = [1,2,3,4]

list.each {
    printn it
}

Collect a.k.a. map

def list = [new SomeObject(name:'first'), new SomeObject(name:'second')]

assert list.collect { it.name } == ['first', 'second']

 

Find

def one = new SomeObject(name:'first')
def two = new SomeObject(name:'second')
def list = [one, two]

assert list.find { it.name == 'first' } == one

 

Elvis

The Elvis operator helps with the following common pattern:

Integer value = null
Integer another = value
if(value == null) {
    another = 15
}

instead of the explicit null check, you can use the Elvis operator:

Integer value = null
Integer another = value ?: 15

// another is 15

Caveat: Elvis uses Groovy truth. If value was 0 (which is considered false) then another would be 15.
 

Interested in working with Groovy?

Look at Careers on our website. While you wait, check out the Groovy documentation.