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

Learning Kotlin: The Map Delegate

DZone 's Guide to

Learning Kotlin: The Map Delegate

Want to learn how to use the map delegate in Kotlin? Check out this post to learn more about using map values in Kotlin.

· Java Zone ·
Free Resource

The next delegate is actually built into something we have looked at before, mapand 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. Then, we 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 initializing 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. 

Happy delegating!

Topics:
java ,kotlin ,delegate ,delegate pattern ,map delegate ,json

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}