https://kotlinlang.org logo
#getting-started
Title
# getting-started
p

Pablo

07/04/2022, 7:23 AM
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

Stephan Schroeder

07/04/2022, 7:37 AM
no
j

Joffrey

07/04/2022, 8:03 AM
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()
.
2 Views