Coming Up for Air

Building Maps in Kotlin

Wednesday, April 08, 2020 |

Over the years, I’ve found myself processing a set of data and storing it in a Map, say, something like Map<Long, List<String>> (think something like a list of Room objects, keyed by a building id). I have found myself writing it something like this (in non-idiomatic Kotlin):

1
2
3
4
5
6
val foo = map.get(key)
if (foo == null) {
    foo = MutableList<String>()
    map.put(key, foo)
}
foo.add(bar)

Fortunately, the Kotlin standard library has a better way:

1
2
map.getOrPut(key) { mutableListOf() }
    .add(bar)

If key is not found, the lambda is run, adding the result to Map and return to use the value, new or otherwise, to which we add bar. Much more concise. :) Generally speaking, any time you can let the language/compiler do the work for you, you’re going to be better off.

Search

    Quotes

    Sample quote

    Quote source

    About

    My name is Jason Lee. I am a software developer living in the middle of Oklahoma. I’ve been a professional developer since 1997, using a variety of languages, including Java, Javascript, PHP, Python, Delphi, and even a bit of C#. I currently work for Red Hat on the WildFly/EAP team, where, among other things, I maintain integrations for some MicroProfile specs, OpenTelemetry, Micrometer, Jakarta Faces, and Bean Validation. (Full resume here. LinkedIn profile)

    I am the president of the Oklahoma City JUG, and an occasional speaker at the JUG and a variety of technical conferences.

    On the personal side, I’m active in my church, and enjoy bass guitar, running, fishing, and a variety of martial arts. I’m also married to a beautiful woman, and have two boys, who, thankfully, look like their mother.

    My Links

    Publications