kotlinbeginner

Delegate Properties to a Map

Store class properties in a map using Kotlin delegation for dynamic and flexible data objects.

kotlin
// 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.