How to make a reference to a sorting function from stdlib? My use case is as follows:
Copy code
fun 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
sortFun
c
CLOVIS
04/16/2024, 12:19 PM
Something like this?
Copy code
fun List<String>.sort(order: String) =
if (order == "asc") sorted() else sortedDescending()
CLOVIS
04/16/2024, 12:21 PM
If you want to know the type of a variable, you can use CTRL SHIFT P in IntelliJ—but I don't understand why you would need this in your example
s
Sam
04/16/2024, 1:47 PM
The reason the example doesn't work is because
sortedBy
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
The type should be
((List<T>, selector: (T) -> R?)
, where
T
is the list items type and
R
is some
Comparable
to act as the sort key
Sam
04/16/2024, 1:48 PM
So for example, this works:
Copy code
fun <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
}
d
David Kubecka
04/17/2024, 7:23 AM
Thanks, Sam. The type is quite complicated so in this case a better option would probably be to duplicate the selector function, i.e.