Last active
May 15, 2018 21:45
-
-
Save carolosf/1a3594421f81d1e7b86f87587f3daa58 to your computer and use it in GitHub Desktop.
Sort objects in Kotlin by dynamically sorted field order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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