Last Updated: February 25, 2016
·
1.56K
· leifhanack

Automatically create in-between maps with Groovy

With the help of withDefault you can easily create in-between maps.

Map person = { [:].withDefault{ owner.call() } }()

// the map *address* will be created if necessary
person.address.zip = "10001"
person.address.street = "5th Av"
person.address.city = "New York"
person.name = "Jeff"

// println
[address:[zip:10001, street:5th Av, city:New York], name:Jeff]

Isn't that groovy?! So elegant, so simple. I love it. This one-liner and the code is much more readable and maintainable: Map person = { [:].withDefault{ owner.call() } }()

Compare this to solutions like get with default or Elvis. Think about deep nested structures. I have a clear winner:)

def person = [:]
def address = person.get('address', [:])
address.zip = "10001"

or

def person = [:]
person["address"] = (person["address"] ?: [:])
person["address"].zip = "10001"

What is your favorite?
Regards, Leif