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? If i want to find first in the list of fooList if the id is equals 1 then change the "foo1" to another string is there any way to avoid to add an else? Otherwise the ide is complaining because I'm not using the result of copy.
Copy code
fun whateverFun(list: List<Foo>, predicate: Int){
  val foundValue = list.find{it.id == predicate}
  foundValue?.let{
    it.copy(title = "foo3"
  }
}
The only way to avoid this warning is to do an if else of a map and in the else remain the same value as it was I did it but I do not like tis..
Copy code
list.map { example -> if(example.id == predicate){example.copy(title="foo3")}else{example.copy(it.title)}
n
You can do
toMutableList()
on the list
which is basically making a copy
and then make the mutation you want on your new mutable list
p
it.copy(newList)?
n
note that
whateverFun
will need to return that new list though
p
no, my fun doesn't return anything
n
well then it's just not going to work
you can't mutate the list that is passed in
your function needs to accept
MutableList
instead of
List
s
well, since the List is probably backed by a MutableList, Pablo could just break the implicit contract of a List being immutable.
Copy code
fooList as? MutableList<Foo> ?: error("fooList should have been mutable")
... // do all the mutation you want on fooList now

https://inktank.fi/wp-content/uploads/2016/11/this-is-fine-gunshow.jpg

(Kotlin collection api extension functions use something like this to be more efficient, but that's because they know/assume(?) the the original list isn't used anymore, and even they return a list like Nir suggested. It's just that depending on if the param is really a MutableList underneath (not all lists are, e.g. classes from kotlinx.collections.immutable) than the cast and modify and return the param, else they create, modify and return a copy.)
If this is the Kotlin version of a Java problem, the parameter should have been
MutableList<Foo>
to start with. Kotlin's
List
is the programming language equivalent of a "false friend" (= easy to make translation mistake) to Java's
List
.
n
None of this is actually a good idea though
s
very true
n
So I'll stick with: either return a
List
, or accept a
MutableList
🙂
j
Copy code
buildList {
    addAll(someList)
    ...
}