Multi-key sort of nullable records with compareBy
Kotlin
data class User(val name: String, val age: Int?, val joined: Long)
fun sortUsers(users: List<User>): List<User> = users.sortedWith(
compareBy<User> { it.age == null }
.thenBy { it.age ?: Int.MAX_VALUE }
.thenByDescending { it.joined }
.thenBy { it.name.lowercase() }
)
val users = listOf(User("bo", null, 2), User("al", 30, 1))
// al first, then bo (null age sorts last)
check(sortUsers(users).map { it.name } == listOf("al", "bo"))