Pablo
07/04/2022, 7:23 AMfun 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
val myList = getList().apply { if(bar) mySorter.sort(this) }
Is there any kotlinian way to sort the list instead of creating a new val?Stephan Schroeder
07/04/2022, 7:37 AMJoffrey
07/04/2022, 8:03 AMList
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:
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()
.