How to make a reference to a sorting function from...
# getting-started
d
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
Something like this?
Copy code
fun List<String>.sort(order: String) =
	if (order == "asc") sorted() else sortedDescending()
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
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.
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
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
Thanks, Sam. The type is quite complicated so in this case a better option would probably be to duplicate the selector function, i.e.
Copy code
if (order == "asc") {
  sortedBy { it.sortingField }
} else {
  sortedByDescending { it.sortingField }
}
Sometimes deduplication efforts are counterproductive 🙂
👍 1