Kotlin

Property Delegation by Map

admin by @admin ADMIN
1d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Delegate a property to a `Map<String, V>` — reading the property fetches by name; writing stores by name. Quick way to back a class with a config map.
Kotlin
Raw
class UserConfig(map: MutableMap<String, Any?>) {
    var theme: String           by map
    var notifications: Boolean  by map
    var refreshIntervalSec: Int by map
}

fun main() {
    val raw = mutableMapOf<String, Any?>(
        "theme"              to "dark",
        "notifications"      to true,
        "refreshIntervalSec" to 60,
    )

    val cfg = UserConfig(raw)
    println(cfg.theme)                              // dark
    println(cfg.notifications)                      // true

    cfg.theme = "light"                              // also updates `raw`
    println(raw["theme"])                            // light

    // Same trick works for immutable read-only:
    class ReadOnlyConfig(map: Map<String, Any?>) {
        val theme: String by map
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.