Skip to Content
Course content

212: Map-Backed Property Delegation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've already seen how delegation can move logic out of your class and into a reusable object. But one of the most practical patterns I use in production—especially when dealing with configuration files or JSON-like data structures—is backing properties with a map. Instead of creating ten different fields for ten different settings, we use a single map and tell Kotlin, "Whenever I touch this property, just go look it up in the map using this specific key."

Turning a Map into a Property Store

Let's imagine we're building a GameSettings class. We have a map of settings that might be loaded from a file, but we want the convenience of strong typing in our code. We don't want to be typing settings["volume"] as Int every time we need to adjust the audio.

I'll start by creating a delegate class. This class needs to implement getValue (and setValue if we want the properties to be mutable). Here is my first attempt:

import kotlin.reflect.KProperty

class MapDelegate(val map: MutableMap<String, Any>, val key: String) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Any? {
        return map[key]
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Any?) {
        map[key] = value!!
    }
}

class GameSettings(val data: MutableMap<String, Any>) {
    var volume: Int by MapDelegate(data, "volume")
    var playerName: String by MapDelegate(data, "playerName")
}

The Type Mismatch Trap

If you try to compile that, the compiler is going to scream at you. I do this all the time when I'm rushing. The problem is that getValue is returning Any?, but our volume property is declared as an Int. Kotlin isn't going to blindly assume that whatever comes out of that map is an integer.

To fix this, we need to leverage generics. We have to tell the delegate what type of data it's actually handling. I'll rewrite the delegate to take a type parameter T. Now, we can cast the value coming out of the map to that type.

class MapDelegate<T>(val map: MutableMap<String, Any>, val key: String) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
        @Suppress("UNCHECKED_CAST")
        return map[key] as T
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        map[key] = value as Any
    }
}

I added @Suppress("UNCHECKED_CAST") because the compiler can't possibly know at runtime that the map actually contains a T. Since we're the ones defining the keys and types in the GameSettings class, we're taking responsibility for that safety.

Putting it all together in the Settings class

Now that the delegate is type-safe, our GameSettings class becomes incredibly clean. We can define as many properties as we want, and they all just map back to that single source of truth.

fun main() {
    val rawData = mutableMapOf<String, Any>(
        "volume" to 80,
        "playerName" to "DragonSlayer99"
    )
    
    val settings = GameSettings(rawData)
    
    println("Player: ${settings.playerName}") // DragonSlayer99
    
    settings.volume = 100 
    println("New volume: ${rawData["volume"]}") // 100
}

What I love about this approach is the separation of concerns. The GameSettings class defines the schema (what settings exist and what their types are), while the MapDelegate handles the mechanism of storage. If you later decide to move these settings from a map to a database or a remote API, you only have to change the delegate logic, not every single property in your class.




📋 Practical Task

Build a Dynamic UserSessionStore

You are tasked with creating a session management system where user data is stored in a map but accessed via properties. Create a class called UserSessionStore that uses a map-backed delegate to manage the following properties:

  • userId (String)
  • loginCount (Int)
  • isPremium (Boolean)

Your implementation must include:

  1. A generic SessionDelegate<T> class that handles the getValue and setValue operations against a MutableMap<String, Any>.
  2. The UserSessionStore class which initializes these three properties using the delegate.
  3. A main function that instantiates the store with an initial map, modifies the loginCount, and prints the updated map to verify the change persisted.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.