这个简单的场景
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(crossinline selector:(T) - > Comparable< *>?):Comparator请明确指定。
将其更改为
println(people.sortedBy{compareBy<Person>{Person::age, Person::name}})
不起作用,
也不起作用println(people.sortedBy{compareBy<Person>{Person::age}.thenBy { Person::name }})
给
错误:(28,20)Kotlin:在内联乐趣中为R绑定的类型参数&gt; Iterable.sortedBy(交叉在线选择器:(T) - &gt; R?):不满足列表:推断类型比较器不是可比较的子类型&gt;
然后我也尝试了多功能重载
println(people.sortedBy{compareBy<Person>({it.age}, {it.name})})
这就产生了
错误:(28,20)Kotlin:在内联乐趣中为R绑定的类型参数&gt; Iterable.sortedBy(交叉在线选择器:(T) - &gt; R?):列表 不满意:推断类型比较器不是Comparable&gt;
的子类型
而且,如果我添加sortedBy
的类型参数
println(people.sortedBy<Person>{compareBy<Person>({it.age}, {it.name})})
这产生完全相同的问题,即
错误:(28,20)Kotlin:在内联乐趣中为R绑定的类型参数&gt; Iterable.sortedBy(交叉在线选择器:(T) - &gt; R?):列表 不满意:推断类型比较器不是Comparable&gt;
的子类型
我做错了什么?
答案 0 :(得分:2)
由sortedWith
和sortedBy
之间的区别所欺骗。事实证明sortedBy
使用单条件(例如sortedBy(Person::name)
),而如果您需要多个条件,则需要sortedWith
:
people.sortedWith(compareBy(Person::age, Person::name))
// or
people.sortedWith(compareBy({ it.age }, { it.name }))