Skip to main content
**More Information**

The next delegate is actually built into something we have looked at before, map and if you use by to refer to one when you get the value it goes to the map values to look it up.

As a way to illustrate this, we will 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, Any?>) {
    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 is happening.

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

This simple adjustment changes the output to be:

Robert with Green eyes and is 36 years oldException 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 is not initialising the values ahead of time. Rather it is merely being used to look up what value in the map when the properties getter is called.