了解Kotlin比较语法

dashenswen

背景:我是kotlin的新手,并且在Java方面有一些经验。

问题:我正在阅读kotlin intellij教程,以了解有关集合和使用sort*函数的方式,但是我对语法感到困惑。

使用kotlinsortedByDescending函数编写的代码

// 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
        }

KotlinsortedByDescending函数的定义

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

据我了解,该sortedByDescending函数接受一个输入类型为T的函数,并返回一个类型为type的输出Comparable<R>> Iterable<T>

  1. 返回类型是什么意思?它看起来像R需要落实Comparable,但也需要一个IteratableT我的理解正确吗?
  2. 如果我的理解是正确的,那该如何it.orders.size适应呢?我知道it在kotlin中用于lambda中的单个参数
罗比·科尼利森(Robby Cornelissen)

我认为您在混淆方法签名的不同部分:

public inline fun <T, R : Comparable<R>> 
    Iterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T> {
  
  return sortedWith(compareByDescending(selector))
}
  • <T, R : Comparable<R>>
    这些是类型参数。该函数接受两个类型参数:T,可以是任何类型的参数;以及R,它受上限限制Comparable<R>(即R只能替换的子类型Comparable<R>)。
  • Iterable<T>
    这是sortedByDescending()可以在其上调用函数的对象的类型
  • List<T>
    这是函数的返回类型。

放在一起,sortedByDescending()功能

  • 可以在类型的目标上调用Iterable<T>;
  • 以lambda表达式作为参数,它需要将typeT的值转换为type的值R,其中whereR必须为Comparable;
  • 返回类型为的结果List<T>

在这种特定情况下,客户列表按每个客户的订单数(it.orders.size降序排列

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章