Kotlin Map Delegation
A property can delegate to a map with by map, so each read looks the property name up as a key. The map becomes the storage, and the property stays a typed view over one entry.
Two properties over one map
Config holds the map and declares host and port over it. Each read finds the entry whose key matches the property name.
class Config(val map: Map<String, Any>) {
val host: String by map
val port: Int by map
}
fun main() {
val map = mapOf("host" to "example.org", "port" to 8080)
val config = Config(map)
println(config.host)
println(config.port)
}Changing the map changes the read
Settings reads host from a MutableMap. Writing a new value into the map itself makes the next read of the property print the new host.
class Settings(val map: MutableMap<String, Any>) {
val host: String by map
}
fun main() {
val map = mutableMapOf<String, Any>("host" to "example.org")
val settings = Settings(map)
println(settings.host)
map["host"] = "kotlin.dev"
println(settings.host)
}A port swap through the map
Server exposes host and port over one mutable map. Replacing the port entry in the map moves the next port read from 8080 to 9090.
class Server(val map: MutableMap<String, Any>) {
val host: String by map
val port: Int by map
}
fun main() {
val map = mutableMapOf<String, Any>("host" to "example.org", "port" to 8080)
val server = Server(map)
println(server.host)
println(server.port)
map["port"] = 9090
println(server.port)
}Example
class Profile(val map: MutableMap<String, Any>) {
val name: String by map
val age: Int by map
}
fun main() {
val map = mutableMapOf<String, Any>("name" to "Ana", "age" to 31)
val profile = Profile(map)
println(profile.name)
println(profile.age)
map["name"] = "Bea"
println(profile.name)
}Key points
- The property name is the key, so a property named host reads the entry stored under "host".
- The declared property type decides how the stored value is read.
- A read only map fits val properties that never change.
- With a MutableMap behind the properties, changing the map changes the next read.
- A missing key fails at run time, so the map and the properties must agree on names.
In this example, Profile declares name and age over a mutable map. The reads print Ana and 31 from the matching entries. Writing Bea into the map under the name key changes the next read of the name property.
Note
Map delegation suits settings and records that already arrive as key and value data.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
How does a property delegated by map find its value?