Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
212: Map-Backed Property Delegation
You've already seen how delegation can move logic out of your class and into a reusable object. But one of the most practical patterns I use in production—especially when dealing with configuration files or JSON-like data structures—is backing properties with a map. Instead of creating ten different fields for ten different settings, we use a single map and tell Kotlin, "Whenever I touch this property, just go look it up in the map using this specific key."
Turning a Map into a Property Store
Let's imagine we're building a GameSettings class. We have a map of settings that might be loaded from a file, but we want the convenience of strong typing in our code. We don't want to be typing settings["volume"] as Int every time we need to adjust the audio.
I'll start by creating a delegate class. This class needs to implement getValue (and setValue if we want the properties to be mutable). Here is my first attempt:
import kotlin.reflect.KProperty
class MapDelegate(val map: MutableMap<String, Any>, val key: String) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): Any? {
return map[key]
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Any?) {
map[key] = value!!
}
}
class GameSettings(val data: MutableMap<String, Any>) {
var volume: Int by MapDelegate(data, "volume")
var playerName: String by MapDelegate(data, "playerName")
}
The Type Mismatch Trap
If you try to compile that, the compiler is going to scream at you. I do this all the time when I'm rushing. The problem is that getValue is returning Any?, but our volume property is declared as an Int. Kotlin isn't going to blindly assume that whatever comes out of that map is an integer.
To fix this, we need to leverage generics. We have to tell the delegate what type of data it's actually handling. I'll rewrite the delegate to take a type parameter T. Now, we can cast the value coming out of the map to that type.
class MapDelegate<T>(val map: MutableMap<String, Any>, val key: String) {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
@Suppress("UNCHECKED_CAST")
return map[key] as T
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
map[key] = value as Any
}
}
I added @Suppress("UNCHECKED_CAST") because the compiler can't possibly know at runtime that the map actually contains a T. Since we're the ones defining the keys and types in the GameSettings class, we're taking responsibility for that safety.
Putting it all together in the Settings class
Now that the delegate is type-safe, our GameSettings class becomes incredibly clean. We can define as many properties as we want, and they all just map back to that single source of truth.
fun main() {
val rawData = mutableMapOf<String, Any>(
"volume" to 80,
"playerName" to "DragonSlayer99"
)
val settings = GameSettings(rawData)
println("Player: ${settings.playerName}") // DragonSlayer99
settings.volume = 100
println("New volume: ${rawData["volume"]}") // 100
}
What I love about this approach is the separation of concerns. The GameSettings class defines the schema (what settings exist and what their types are), while the MapDelegate handles the mechanism of storage. If you later decide to move these settings from a map to a database or a remote API, you only have to change the delegate logic, not every single property in your class.
📋 Practical Task
Build a Dynamic UserSessionStore
You are tasked with creating a session management system where user data is stored in a map but accessed via properties. Create a class called UserSessionStore that uses a map-backed delegate to manage the following properties:
userId(String)loginCount(Int)isPremium(Boolean)
Your implementation must include:
- A generic
SessionDelegate<T>class that handles thegetValueandsetValueoperations against aMutableMap<String, Any>. - The
UserSessionStoreclass which initializes these three properties using the delegate. - A
mainfunction that instantiates the store with an initial map, modifies theloginCount, and prints the updated map to verify the change persisted.
There are no comments for now.