Sort data from a MutableList in Kotlin

VTR2015 picture VTR2015 · Oct 22, 2017 · Viewed 14.4k times · Source

I'm new to Kotlin and need to ask some questions about ordering a MutableList<MyObject>. As I understand it, I can do a myMutableList.sortBy {it.int} and a myMutableList.sortByDescending {it.int} for both Int and String. But return is always a Unit and not a MutableList.

Where am I going wrong and how do I proceed?

Answer

weston picture weston · Oct 22, 2017

Mutable means changeable, so it makes sense that rather than sortBy returning a new list, the order of the items has changed "in place" in the current list.

Try looking at the order of the items in myMutableList after the sortBy and you will see they are now in the order requested.