多态类有序的隐式展开

时间:2018-11-24 21:51:13

标签: scala implicit

为什么我在以下代码中遇到diverging implicit expansion编译器异常?

trait Person extends Ordered [Person] {
    def age: Int
    def compare (that: Person) = this.age.compare(that.age)
}

class Dinner[A <: Person](val people: Seq[A]) {
    def who = people.sorted
}


<console>:16: error: diverging implicit expansion for type scala.math.Ordering[A]
starting with method $conforms in object Predef
           def who = people.sorted
                            ^

好的,我可以使用people.sorted[Person],但是为什么我应该A是它的子类。

1 个答案:

答案 0 :(得分:1)

您指定了如何比较Person,但是您没有为A <: Person做比较,并且在people.sorted中,编译器必须知道如何进行比较。

尝试

trait Person extends Ordered [Person] { 
  def age: Int
  def compare(that: Person): Int = implicitly[Ordering[Person]].compare(this, that)
}

implicit def personOrdering[A <: Person]: Ordering[A] = (x, y) => x.age.compare(y.age)

class Dinner[A <: Person](val people: Seq[A]) {
  def who: Seq[A] = people.sorted
}

case class PersonImpl(age: Int) extends Person
val dinner = new Dinner[PersonImpl](Seq(PersonImpl(30), PersonImpl(20)))
dinner.who // List(PersonImpl(20), PersonImpl(30))