`val fullTariffList = arrayOf("customer", "reselle...
# announcements
c
val fullTariffList = arrayOf("customer", "reseller", "vendor").flatMap { type ->  testTariffList.map { it.copy(type = type) } }
1
K 1
m
Thanks, your solution is perfect) But I also want to understand what is going on in my example)
Why
fullTariffList.add(tariffInfo)
is always contains
vendor
. I think I am missing some knowledge about
forEach
r
You are basically adding one item three times into the list.
m
but
println(tariffInfo);
shows me that tariffInfo is different in every iteration
fullTariffList.add(tariffInfo)
processed after finishing forEach?
May be someone could point me to docs)
r
Copy code
class Object { var type: String }

val list = mutableListOf<Object>()
val obj = Object()

obj.type = "1"
println(obj.type) // "1"
list += obj // list has one reference to obj, it's type is "1"

obj.type = "2"
println(obj.type) // "2"
list += obj // list has two reference to the same obj, it's type is "2"

obj.type = "3"
println(obj.type) // "3"
list += obj // list has three reference to the same obj, it's type is "3"

list.forEach {
    println(it.type)
}
// prints "3 3 3", as it's the same object and last value of type was "3"
Does it make this clearer? If you are coming from the language with pointers: your container holds objects by reference, not by value. So
.copy
allows you to create new object every iteration and list would have different objects inside it.
👍 1
m
Yeah, I got your example
Thank you
n
that
flatMap
solution creates a list with the same items but in a different order than the original code. Turning it inside out would fix this:
Copy code
testTariffList.flatMap { item -> arrayOf("customer", "reseller", "vendor").map { item.copy(type = it) } }
m
in general, order does not matter. Neverthless it's useful example, thanks