Skip to content

Instantly share code, notes, and snippets.

@carolosf
Last active May 15, 2018 21:45
Show Gist options
  • Save carolosf/1a3594421f81d1e7b86f87587f3daa58 to your computer and use it in GitHub Desktop.
Save carolosf/1a3594421f81d1e7b86f87587f3daa58 to your computer and use it in GitHub Desktop.
Sort objects in Kotlin by dynamically sorted field order
data class User(val id: String, val email: String, val title: String)
val sortedById = {u : User -> u.id}
val sortedByEmail = {u : User -> u.email}
val sortOrder = listOf("id", "email")
val transformedSortOrderListToComparable = sortOrder.map {
when (it) {
"id" -> sortedById //Can inline
"email" -> sortedByEmail //Can inline
else -> throw IllegalArgumentException("Not supported")
}
}
val userList = listOf(
User("1","b","a"),
User("1","a","b")
)
val sorted = userList.sortedWith(compareBy(*transformedSortOrderListToComparable.toTypedArray()))
println(sorted) //title b comes first as expected
//[User(id=1, email=a, title=b), User(id=1, email=b, title=a)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment