Dark theme | Light theme

July 14, 2010

Groovy Goodness: Map with Default Values

In Groovy we can create a map and use the withDefault() method with a closure to define default values for keys that are not yet in the map. The value for the key is then added to the map, so next time we can get the value from the map.

def m = [start: 'one'].withDefault { key -> 
    key.isNumber() ? 42 : 'Groovy rocks!'

assert 'one' == m.start
assert 42 == m['1']
assert 'Groovy rocks!' == m['I say']
assert 3 == m.size()

// We can still assign our own values to keys of course:
m['mrhaki'] = 'Hubert Klein Ikkink'
assert 'Hubert Klein Ikkink' == m.mrhaki
assert 4 == m.size()