Kotlin多标准排序不编译

时间:2017-01-04 10:30:42

标签: sorting collections kotlin

这个简单的场景

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;

的子类型

我做错了什么?

1 个答案:

答案 0 :(得分:2)

sortedWithsortedBy之间的区别所欺骗。事实证明sortedBy使用条件(例如sortedBy(Person::name)),而如果您需要多个条件,则需要sortedWith

people.sortedWith(compareBy(Person::age, Person::name))
// or
people.sortedWith(compareBy({ it.age }, { it.name }))