David Kubecka
04/16/2024, 11:46 AMfun List<String>.sort(order: String) {
val sortFun = if (order == "asc") List<String>::sortedBy else List<String>::sortedByDescending
}
I can't figure out the right typing for sortFunCLOVIS
04/16/2024, 12:19 PMfun List<String>.sort(order: String) =
if (order == "asc") sorted() else sortedDescending()CLOVIS
04/16/2024, 12:21 PMSam
04/16/2024, 1:47 PMsortedBy and sortedByDescending have two type parameters, one for the list items and another for the sort key. The first can be inferred from context, but the second would need to be specified.Sam
04/16/2024, 1:47 PM((List<T>, selector: (T) -> R?), where T is the list items type and R is some Comparable to act as the sort keySam
04/16/2024, 1:48 PMfun <T, R: Comparable<R>> List<T>.sort(order: String) {
val sortFun: ((List<T>, selector: (T) -> R?) -> List<T>) =
if (order == "asc") List<T>::sortedBy else List<T>::sortedByDescending
}David Kubecka
04/17/2024, 7:23 AMif (order == "asc") {
sortedBy { it.sortingField }
} else {
sortedByDescending { it.sortingField }
}
Sometimes deduplication efforts are counterproductive 🙂