March 3, 2020

Groovy Goodness: Safe Index Based Access For Lists, Arrays and Maps

Groovy 3 adds the feature of safe index based access for lists, arrays and maps. This means we can use ?[index] to get or a set a value on a list or array without getting a NullPointerException when the list or array is not initialised. With maps we can use ?[key] for getting a value or set a value and when the map object is not initialised we don't get a NullPointerException.

In the following example we see several examples of setting or getting values using indices or keys:

def list = null

// Accessing null list or array 
// using index based access, 
// will throw NullPointerException when
// collection is null.
try {
} catch (NullPointerException npe) {
    assert npe

// Using ?[...] will not throw NullPointerException.
assert list?[0] == null

// Assignment are ignored when list is null.
list?[1] = 42
assert list?[1] == null

// When collection is not null we simply
// get the default behaviour for index based
// access of elements.
def values = ["Groovy", "rocks"]
assert values?[0] == "Groovy"
values?[2] = '!'
assert values?.join(" ") == "Groovy rocks !"

// We can use ?[key] for maps as well.
def info = null
assert info?['address'] == null
info?['address'] = 'unknown'
assert info?['address'] == null

def user = [alias: 'mrhaki', loves: 'Groovy']
assert user?['alias'] == 'mrhaki'
user?['country'] = 'The Netherlands'
assert user?['country'] == 'The Netherlands'
assert user?['age'] == null

Written with Groovy 3.0.1.