Zorgan
Zorgan

Reputation: 9153

sortedBy() selector not sorting List

I have a sortedBy{} statement which intends to sort a List by the length of the String elements:

var animals: List<String> = listOf("tiger", "cat", "dragon", "elephant")
fun strLength(it: String) = it.length
animals.sortedBy { strLength(it) }
animals.forEach {println(it)}

However it only prints the initial order. Any idea why?

Upvotes: 2

Views: 1088

Answers (2)

Laksitha Ranasingha
Laksitha Ranasingha

Reputation: 4517

You have to assign the output of sortedBy.

  animals = animals.sortedBy { strLength(it) }

Because, like many other functions in Kotlin, sortedBy doesn’t mutate the input & honour immutability. So it returns a new collection. So it mitigates side-effects. Kotlin encourages this immutable approach. However, there are mutable counterparts of these collections if required.

Upvotes: 5

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16795

sortedBy does not sort the list, instead it returns a new list which has the elements sorted. If you don't want a new list, simply use sortBy.

Upvotes: 4

Related Questions