Groovy Goodness: Unmodifiable Collections
When we wanted to create collections in Groovy that were unmodifiable we could use asImmutable.
Since Groovy 2.5.0 we can also use the asUnmodifiable
method on collections.
The method can be applied on all Collection
types including Map
.
In the following example we use asUnmodifiable
on a List
and Map
:
import static groovy.test.GroovyAssert.shouldFail
// Create List that is unmodifiable.
def list = ['Groovy', 'Gradle', 'Asciidoctor', 'Micronaut'].asUnmodifiable()
shouldFail(UnsupportedOperationException) {
// We cannot add new items.
list << 'Java'
}
shouldFail(UnsupportedOperationException) {
// We cannot change items.
list[0] = 'Java'
}
// Create Map that is unmodifiable.
def data = [name: 'Messages from mrhaki', subject: 'Gr8 stuff'].asUnmodifiable()
shouldFail(UnsupportedOperationException) {
// We cannot add a new key.
data.subject = 'Dev subjects'
}
shouldFail(UnsupportedOperationException) {
// We cannot change the value of a key.
data.blog = true
}
Written with Groovy 2.5.0.