这个简单的场景
data class Person(var name:String, var age:Int)
var people = listOf(
Person("Adam", 36),
Person("Boris", 18),
Person("Claire", 36),
Person("Adam", 20),
Person("Jack", 20)
)
println(people.sortedBy{compareBy{Person::age, Person::name}})
不编译
错误:(27,29)Kotlin:类型推断失败:没有足够的信息来推断内联中的参数T> fun compareBy(交叉在线选择器:(T) - >可比较<*>?):比较器请明确指定它 .
将其更改为
println(people.sortedBy{compareBy<Person>{Person::age, Person::name}})
不起作用,也不起作用
println(people.sortedBy{compareBy<Person>{Person::age}.thenBy { Person::name }})
给
错误:(28,20)Kotlin:在内联乐趣中输入R的类型参数> Iterable.sortedBy(交叉在线选择器:(T) - > R?):不满足列表:推断类型比较器不是Comparable的子类型>
那么我也尝试了多功能过载
println(people.sortedBy{compareBy<Person>({it.age}, {it.name})})
这就产生了
错误:(28,20)Kotlin:在内联乐趣中输入R的类型参数> Iterable.sortedBy(交叉在线选择器:(T) - > R?):不满足列表:推断类型比较器不是Comparable的子类型>
而且,如果我也为 sortedBy
添加了类型参数,那就更有趣了
println(people.sortedBy<Person>{compareBy<Person>({it.age}, {it.name})})
这产生完全相同的问题,即
错误:(28,20)Kotlin:在内联乐趣中输入R的类型参数> Iterable.sortedBy(交叉在线选择器:(T) - > R?):不满足列表:推断类型比较器不是Comparable的子类型>
我究竟做错了什么?
1 回答
被
sortedWith
和sortedBy
之间的区别所欺骗 . 事实证明sortedBy
使用单一标准(例如,sortedBy(Person::name)
),而如果您想要多个标准,则需要sortedWith
: