Delegates for Preferences, Map-Backed Properties & Logging
Apply delegates to SharedPreferences, Map storage, and audit logging.
Map-Backed Properties
Kotlin allows delegating properties to a Map directly. Reading the property looks up its name in the map.
class User(map: Map<String, Any?>) {
val name: String by map
val age: Int by map
}
fun main() {
val u = User(mapOf("name" to "Alice", "age" to 30))
println(u.name) // Alice
println(u.age) // 30
}MutableMap Delegate
For mutable properties, delegate to a MutableMap and mutations update the underlying map.
class Settings(private val map: MutableMap<String, Any?> = mutableMapOf()) {
var theme: String by map
var fontSize: Int by map
}
fun main() {
val s = Settings()
s.theme = "dark"
s.fontSize = 16
println(s.theme) // dark
println(s.fontSize) // 16
}All lessons in this course
- by lazy: Deferred Initialization Deep Dive
- observable and vetoable Delegates
- Writing a Custom ReadWriteProperty Delegate
- Delegates for Preferences, Map-Backed Properties & Logging