davec
03/29/2019, 4:38 PMString
, for example) this would work fine. However in the case below where the return type is Any
, it doesn't work.
data class Foo(val name:String, val age:Int)
val sortModes = mapOf("name" to Foo::name, "age" to Foo::age)
val myList = listOf(Foo("Dog", 17), Foo("Cat", 12), Foo("Mouse", 3))
val sortFunc = sortModes["name"] ?: error("Not found") // returns KProperty1<Foo, Any>
println(myList.sortedWith(compareBy(sortFunc)) // <-- compiler error
What magic is required to get Kotlin to sort by a function reference that can return Any
?davec
03/29/2019, 4:49 PMprintln(myList.sortedWith(compareBy {
val value = sortFunc(it)
when(value) {
is String -> value
is Int -> value
else -> error("unsupported type")
}
}))
hudsonb
03/29/2019, 4:51 PMdata class Foo(val name:String, val age:Int)
val sortModes = mapOf("name" to Comparator { o1, o2 -> o1.name.compareTo(o2.name) },
"age" to Comparator<Foo> { o1, o2 -> o1.age - o2.age })
val myList = listOf(Foo("Dog", 17), Foo("Cat", 12), Foo("Mouse", 3))
val sortFunc = sortModes["name"] ?: error("Not found")
println(myList.sortedWith(sortFunc))
davec
03/29/2019, 5:01 PMdavec
03/29/2019, 5:28 PMval sortModes = mapOf(
"name" to compareBy(Foo::name),
"age" to compareBy(Foo::age)
)
val myList = listOf(Foo("Dog", 17), Foo("Cat", 12), Foo("Mouse", 3))
val sortFunc = sortModes["age"] ?: error("Not found")
println("by name: ${myList.sortedWith(sortFunc)}")
I'm going with that unless anyone has any other suggestions.hudsonb
03/29/2019, 5:41 PMcompareBy
but couldnt think of ithudsonb
03/29/2019, 5:44 PMdavec
03/29/2019, 6:11 PM