https://kotlinlang.org logo
Title
z

ziad

01/19/2018, 5:16 PM
Modifying a map in a data class, is the following a sound approach?
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

jk

01/19/2018, 6:24 PM
since
+
on an immutable map returns a new immutable map anyway, it would be simpler just to write:
fun addElementToMyDataClass(myInstance : MyDataClass, key : Int, value : String): MyDataClass {
    return myInstance.copy(myMap = myInstance.myMap + (key to value))
}
z

ziad

01/19/2018, 6:24 PM
Thanks! (And hello)
j

jk

01/19/2018, 6:24 PM
👋
😄
n

nkiesel

01/19/2018, 7:15 PM
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

ziad

01/19/2018, 7:18 PM
Hey Norbert, I think you may have intended your reply for someone else?