How do I change this List<T>? ```data class ...
# announcements
p
How do I change this List<T>?
Copy code
data class Foo (val id: String, val name: String)
val fooList = listof<Foo>(Foo("1","foo1"),Foo("2","foo22)
Imagine I get this
fooList
as a parameter and I want to update this list, do I need to do a
clone
of the list and then a
copy
of the
data class
and update there the values?
g
this is read only list with immutable data classes, so yes, you have to copy it to modify
p
but if its comming via parameter to a fun then how do I update the val inside the list?
g
you cannot, you have to copy your Foo too
depends how you want to copy it, what it’s doing
if you want to modify every item of the list, it usually looks something like:
Copy code
fun doSomething(list: List<Foo>) {
    val newList = list.map { foo ->
        foo.copy(name = foo.name.uppercase() )
    }
    println(newList)
}
🙌🏽 1
a
also you can convert list to mutable, modify it and convert it back to readonly one something like this:
Copy code
val list = listOf<Any>()
val mutList = list.toMutableList()
// TODO: apply changes to mutList, e.g. add or remove items
val result = mutList.toList()
🙌🏽 1
p
But if I need to do a find first? I mean I want to change just the Foo with a "foo1" I tried your proposals but when I do the if or find it says the value of copy is not used because could be that the list doesn't find the "foo1"
Let's say I have this :
Copy code
val list = List<Foo>

val foundValue = list.find{it.title == "foo1"}
Here I need to change the value of that value
g
still use map
it’s the easiest solution
list.map { if (it.title == “foo1) it.copy(…) else it }