Loading...

October 28, 2009

Groovy Goodness: Immutable Collections

Groovy adds the method asImmutable() to the Collection interface. With this method we can convert a list or map to an immutable one. We can read data from the immutable list or map, but we cannot add, change or remove elements from the list or map. This is a good way to insure our list or map is read only in for example a threading and concurrency context.

def list = ['Groovy', 'Java', 'JRuby'].asImmutable()
assert 'Groovy' == list[0]
try {
    list << 'Scala'  // Cannot add item.
} catch (e) {
    assert e instanceof UnsupportedOperationException
}
try {
    list.remove 'Java'  // Cannot remove item.
} catch (e) {
    assert e instanceof UnsupportedOperationException
}

def map = [name: 'mrhaki', country: 'The Netherlands', blog: true].asImmutable()
assert map.blog
try {
    map.blog = false  // Cannot change item.
} catch (e) {
    assert e instanceof UnsupportedOperationException
}