背景:我是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>
。
R
需要落实Comparable
,但也需要一个Iteratable
的T
。我的理解正确吗?it.orders.size
适应呢?我知道it
在kotlin中用于lambda中的单个参数我认为您在混淆方法签名的不同部分:
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>
;T
的值转换为type的值R
,其中whereR
必须为Comparable
;List<T>
。在这种特定情况下,客户列表按每个客户的订单数(it.orders.size
)降序排列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句