Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness — Unmodifiable Collections [Snippet]

DZone's Guide to

Groovy Goodness — Unmodifiable Collections [Snippet]

Here is a new way to make your collections immutable. Read on for details and an example!

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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 to 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'

    // 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'

    // We cannot change the value of a key.
    data.blog = true
}


Written with Groovy 2.5.0.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,groovy ,collections ,immutable ,code

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}