Paul N
04/30/2020, 9:22 AMaraqnid
04/30/2020, 9:34 AMfun sortForUser(username:String):Comparator<Pair<String, String>>
which ranks by the second propertiesPaul N
04/30/2020, 9:36 AMaraqnid
04/30/2020, 9:39 AMPaul N
04/30/2020, 9:41 AMdiesieben07
04/30/2020, 9:41 AMaraqnid
04/30/2020, 9:43 AM@Test
fun scratchpad() {
val sortByDescription = compareBy<Pair<String, String>> { it.first }
fun rankUser(username: String): Comparator<String> {
return compareBy<String> {
when (it) {
"SYSTEM" -> 0
username -> 1
else -> 2
}
}
}
fun sortForUser(username: String): Comparator<Pair<String, String>> {
return compareBy(rankUser(username)) { it.second }
}
val example = listOf("red" to "xyzzy", "orange" to "SYSTEM", "blue" to "SYSTEM", "green" to "other")
assertEquals(
listOf("blue" to "SYSTEM", "orange" to "SYSTEM", "red" to "xyzzy", "green" to "other"),
example.sortedWith(sortForUser("xyzzy").then(sortByDescription))
)
assertEquals(
listOf("blue" to "SYSTEM", "orange" to "SYSTEM", "green" to "other", "red" to "xyzzy"),
example.sortedWith(sortForUser("other").then(sortByDescription))
)
}
araqnid
04/30/2020, 9:44 AMcompareBy
and .then
here)diesieben07
04/30/2020, 9:45 AMaraqnid
04/30/2020, 9:45 AMthen
is an infix function, that looks nicer. It’s just a quick draft 🙂araqnid
04/30/2020, 9:54 AMsortByDescription
to delegate/return 0 based on the user. At least, that’s my understanding of the stable sortdiesieben07
04/30/2020, 9:54 AMJakub Pi
04/30/2020, 4:13 PMComparator
interface (see thenComparing
), I would advise that the domain model probably needs restructuring especially if this is not a one-off use case.