0Pricing
Kotlin Academy · Lesson

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

  1. by lazy: Deferred Initialization Deep Dive
  2. observable and vetoable Delegates
  3. Writing a Custom ReadWriteProperty Delegate
  4. Delegates for Preferences, Map-Backed Properties & Logging
← Back to Kotlin Academy