I know it's possible to do ```class Blah(val map: ...
# random
j
I know it's possible to do
Copy code
class Blah(val map: Map<String, Any>) {
    val value1: String by map
    val value2: String by map
    val value3: Boolean by map
}
and now I can do
Copy code
val blah = Blah(mapOf("value1" to "...", ...)); 

println(blah.value1)
println(blah.value2)
println(blah.value3)
wouldn't it be cool if you could do
Copy code
data class Blah(
        val value1: String,
        val value2: String,
        val value3: Boolean,
    ) {

        constructor(map: Map<String, Any>): this(
            value1 by map,
            value2 by map
            value3 by map
        )
    }
now I can do
Copy code
Blah(map).copy(value3 = ...)
Just a random thought ...
k
The thing is, in the original
Blah
, every time you access a value in Blah, you're actually doing a lookup in the map. In your proposed data class constructor, how would you implement it so that there is only one map but you have two instances of Blah with different values?
j
You'll need two classes probably The second example, I'm hoping to once-off copy the values from the map via map delegates which would effectively be
Copy code
data class Blah(
        val value1: String,
        val value2: String,
        val value3: Boolean,
    ) {

        constructor(map: Map<String, Any>): this(
            value1 = map["value1"],
            value2 = map["value2"],
            value3 = map["value3"],
        )
    }
but
by
doesn't seem to work in that context
Copy code
class BlahFromMap(map: Map<String, Any>)
and then class Blah with a second constructor which takes BlahFrom map as a type and then manually copying data over Probably something that can be solved with KSP to generate helper classes that can be instantiated from a Map ... or I could just use Serialization ­čśä
the original use-case was how to add data to a map in a type-safe way and then I wanted
Copy code
class MutableUser(val map: MutableMap<String, Any?>) {
    var name: String by map
    var age: Int     by map
}
but also have the niceties of a data class