https://kotlinlang.org logo
Title
j

janvladimirmostert

01/31/2023, 12:02 PM
I know it's possible to do
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
val blah = Blah(mapOf("value1" to "...", ...)); 

println(blah.value1)
println(blah.value2)
println(blah.value3)
wouldn't it be cool if you could do
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
Blah(map).copy(value3 = ...)
Just a random thought ...
k

Klitos Kyriacou

01/31/2023, 12:47 PM
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

janvladimirmostert

01/31/2023, 12:56 PM
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
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
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
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