Pablo
05/31/2021, 2:07 PMdata 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.
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..
list.map { example -> if(example.id == predicate){example.copy(title="foo3")}else{example.copy(it.title)}
Nir
05/31/2021, 2:13 PMtoMutableList()
on the listNir
05/31/2021, 2:13 PMNir
05/31/2021, 2:13 PMPablo
05/31/2021, 2:14 PMNir
05/31/2021, 2:14 PMwhateverFun
will need to return that new list thoughPablo
05/31/2021, 2:14 PMNir
05/31/2021, 2:14 PMNir
05/31/2021, 2:14 PMNir
05/31/2021, 2:14 PMMutableList
instead of List
Stephan Schroeder
05/31/2021, 2:50 PMfooList 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▾
Stephan Schroeder
05/31/2021, 2:54 PMMutableList<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
.Nir
05/31/2021, 3:03 PMStephan Schroeder
05/31/2021, 3:03 PMNir
05/31/2021, 3:03 PMList
, or accept a MutableList
🙂Javier
05/31/2021, 5:15 PMbuildList {
addAll(someList)
...
}