Hello how can I update a list for instance. I have...
# getting-started
p
Hello how can I update a list for instance. I have this
Copy code
fun getList() : List<Foo>

val myList = getList()
Now I want depending on my flag sort or not that list, I've tried it but did not work
Copy code
val myList = getList().apply { if(bar) mySorter.sort(this) }
Is there any kotlinian way to sort the list instead of creating a new val?
s
no
j
The
List
type represents read-only lists. If you're getting such a list, you can't modify it, but you can create a new list with sorted elements by using
myList.sorted()
. You don't have to create a new variable though:
Copy code
val myList = getList().let { if(bar) it.sorted() else it }
Now if you created your own implementation of sorter that works in-place (and modifies the initial list), you will first have to create a mutable copy of the list, for instance by using
getList().toMutableList()
.