Learning Kotlin: The map delegate

Note *This is the 28th post in a multipart series. If you want to read more, see our series index *This follows the introduction to the by operator and delegates.

The next delegate is actually built into something we’ve looked at before—map—and if you use by to refer to one when you get the value, it looks up the map’s values. As a way to illustrate this, we’ll take some JSON data and parse it with the kotlinx.serialization code. We then loop over each item and convert it into a map, which we use to create an instance of User.

import kotlinx.serialization.json.*
class User(userValues: Map<String, String>) {
    val name: String by userValues
    val eyeColour: String by userValues
    val age: String by userValues
}

fun main(args: Array<String>) {
    val json = """[{ "name":"Robert", "eyeColour":"Green", "age":36 },{ "name":"Frank", "eyeColour":"Blue" }]"""
    (JsonTreeParser(json).read() as JsonArray)
        .map { val person = it as JsonObject
               person.keys.associateBy({ it }, { person.getPrimitive(it).content })
        }.map { User(it) }
        .forEach { println("${it.name} with ${it.eyeColour} eyes") }
}

This code outputs:

Robert with Green eyes
Frank with Blue eyes

However, if we change line 25 to include the age, we get a better view of what’s happening:

}.forEach { println("${it.name} with ${it.eyeColour} eyes and is ${it.age} years old") }

This simple adjustment changes the output to:

Robert with Green eyes and is 36 years old
Exception in thread "main"
java.util.NoSuchElementException: Key 'age' is missing in the map.
        at kotlin.collections.MapsKt__MapWithDefaultKt.getOrImplicitDefaultNullable(MapWithDefault.kt:24)
        at sadev.User.getAge(blog.kt)
        at sadev.BlogKt.main(blog.kt:27)

As you can see, the map isn’t initializing the values ahead of time. Instead, it’s merely used to look up a value in the map when the property’s getter is called.