Sorting a collection by multiple fields in Kotlin
Hello everyone! I just started learning Kotlin and came across a task that seems simple, but I can't find an elegant solution.
I have a list of `Person` class objects:
```kotlin
data class Person(
val name: String,
val age: Int,
val salary: Double
)
```
I need to sort this list first by age (ascending), then, if the age is the same, by name (alphabetical order), and finally, if both age and name match, by salary (descending).
In Java, I would use a chain of comparators, but in Kotlin I see there is a `sortedBy` function, but it only takes one field. There is `sortedWith` and `compareBy`, but I don't fully understand how to combine them correctly.
I tried this code:
```kotlin
val sortedList = list.sortedBy
No answers yet.
Log in to leave an answer