Understand Kotlin Comparison Syntax

Viewed 131

Background: I am new to kotlin and has some experience in java.

Problem: I am going through the kotlin intellij tutorial to learn about collections and the way to use the sort* functions but I am confused about the syntax.

The code written to use the kotlin sortedByDescending function :

// Return a list of customers, sorted in the descending by number of orders they have made
fun Shop.getCustomersSortedByOrders(): List<Customer> =
        customers.sortedByDescending {
            it.orders.size // I am confused here
        }

the definition of kotlin sortedByDescending function

public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T> {
    return sortedWith(compareByDescending(selector))
}

To my understanding, the sortedByDescending takes a function which input type is T and returns an output in type Comparable<R>> Iterable<T>.

  1. what does the return type mean? it looks like R needs to implement the Comparable but also needs to be an Iteratable of T . Is my understanding correct?
  2. if my understanding is right, the how does it.orders.size fit into that type? I know it in kotlin is used for single params in lambda
1 Answers

I think you're confusing the different parts of the method signature:

public inline fun <T, R : Comparable<R>> 
    Iterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T> {
  
  return sortedWith(compareByDescending(selector))
}
  • <T, R : Comparable<R>>
    These are the type parameters. The function takes two type parameters: T, which can be anything, and R, which is restricted by the upper bound Comparable<R> (i.e. R may only be substituted for a subtype of Comparable<R>).
  • Iterable<T>
    This is the type of objects on which the sortedByDescending() function can be invoked.
  • List<T>
    This is the return type of the function.

Putting it all together, the sortedByDescending() function

  • can be invoked on targets of type Iterable<T>;
  • takes a lambda expression as an argument, which needs to transform a value of type T into a value of type R, where R needs to be Comparable;
  • returns a result of type List<T>.

In this specific case, the list of customers is sorted in descending order by the number of orders per customer (it.orders.size).

Related