Modifying a map in a data class, is the following ...
# announcements
z
Modifying a map in a data class, is the following a sound approach?
Copy code
data class MyDataClass(
        val myMap: Map<Int, String> = mapOf()
)

fun addElementToMyDataClass(myInstance : MyDataClass, key : Int, value : String): MyDataClass {
    val mutableCopyOfMap = myInstance.myMap.toMutableMap()
    mutableCopyOfMap[key] = value
    return myInstance.copy(myMap = mutableCopyOfMap)
}
j
since
+
on an immutable map returns a new immutable map anyway, it would be simpler just to write:
Copy code
fun addElementToMyDataClass(myInstance : MyDataClass, key : Int, value : String): MyDataClass {
    return myInstance.copy(myMap = myInstance.myMap + (key to value))
}
z
Thanks! (And hello)
j
👋
😄
n
Your original approach also would work if you would use
fullTariffList.add(tariffInfo.copy())
. Your problem is that the fullTariffList contains pointers to the objects. So you really have (A,B,A,B,A.B) in your list and thus setting the type to "vendor" in the last loop iteration modifies all entries
z
Hey Norbert, I think you may have intended your reply for someone else?