Map Delegation

Properties Backed by a Map

A property can read its value from a Map using the property name as the key. Useful for JSON-like data, config files and dynamic attributes.

Example

class Config(map: Map<String, Any?>) {
    val appName: String by map
    val maxUsers: Int by map
    val darkMode: Boolean by map
}

class MutableSettings(val values: MutableMap<String, Any?>) {
    var language: String by values
    var fontSize: Int by values
}

fun main() {
    val config = Config(mapOf("appName" to "Careeroza", "maxUsers" to 500, "darkMode" to true))
    println("${config.appName} allows ${config.maxUsers} users, dark mode = ${config.darkMode}")

    val settings = MutableSettings(mutableMapOf("language" to "en", "fontSize" to 14))
    settings.language = "hi"
    settings.fontSize += 2
    println(settings.values)
}

Output

Careeroza allows 500 users, dark mode = true
{language=hi, fontSize=16}

Note: A missing key throws NoSuchElementException when the property is read; a wrong type throws ClassCastException.