kotlinbeginner
Delegate Properties to a Map
Store class properties in a map using Kotlin delegation for dynamic and flexible data objects.
kotlinPress ⌘/Ctrl + Shift + C to copy
// Delegate properties to a Map
class DynamicConfig(private val map: Map<String, Any?>) {
val host: String by map
val port: Int by map
val debug: Boolean by map
}
// Mutable version uses MutableMap
class MutableConfig(private val map: MutableMap<String, Any?>) {
var host: String by map
var port: Int by map
var debug: Boolean by map
}
// JSON-like dynamic object
class JsonRow(private val data: Map<String, Any?>) {
val id: Int by data
val name: String by data
val email: String by data
override fun toString() = "JsonRow(id=$id, name=$name, email=$email)"
}
fun main() {
// Immutable config from map
val config = DynamicConfig(mapOf(
"host" to "localhost",
"port" to 8080,
"debug" to true
))
println("Host: ${config.host}, Port: ${config.port}, Debug: ${config.debug}")
// Mutable config
val mutableConfig = MutableConfig(mutableMapOf(
"host" to "localhost",
"port" to 3000,
"debug" to false
))
mutableConfig.host = "production.server.com"
mutableConfig.port = 443
println("Updated: ${mutableConfig.host}:${mutableConfig.port}")
// Simulating JSON rows from an API
val rows = listOf(
mapOf("id" to 1, "name" to "Alice", "email" to "alice@test.com"),
mapOf("id" to 2, "name" to "Bob", "email" to "bob@test.com"),
mapOf("id" to 3, "name" to "Carol", "email" to "carol@test.com")
).map { JsonRow(it) }
rows.forEach { println(it) }
}Use Cases
- Dynamic configuration from external sources
- JSON-to-object mapping without libraries
- Flexible data transfer objects
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
kotlinintermediate
Delegation — by, lazy, observable, and Custom
Use Kotlin delegation for reusable behavior: by keyword, lazy, observable, vetoable, and map-backed.
Best for: Composing behavior without deep inheritance
#kotlin#delegation
kotlinintermediate
Map Delegation for Dynamic Properties
Delegate properties to maps: dynamic configuration, JSON-to-object mapping, and flexible data classes.
Best for: Dynamic configuration loading
#kotlin#delegation
kotlinadvanced
Custom Property Delegates
Create reusable property delegates: validation, logging, caching, and thread-safe lazy initialization.
Best for: Input validation on property assignment
#kotlin#delegates
kotlinintermediate
Interface Delegation with 'by'
Delegate interface implementations with the 'by' keyword: composition over inheritance patterns.
Best for: Composition over inheritance
#kotlin#delegation