Scala中有序特征的问题

时间:2014-10-19 01:14:09

标签: scala natural-sort

我试图为不同但类似的对象类定义一个自然排序。在Java中,我会使用Comparable,似乎在Scala中使用Ordered进行等效的方法。我有以下特点:

trait Positioned extends Ordered[Positioned] {
  def position: Int = 1

  override def compare(that: Positioned): Int = position - that.position
}

我想将这个特性应用于多个案例类,如下所示:

case class Image(id: String,
                 override val position: Int = 1) extends Positioned

这很合适但在运行时我在这些sorted对象的集合上调用Image时,我收到此错误:

diverging implicit expansion for type scala.math.Ordering[com.myapp.Image]
starting with method $conforms in object Predef

请让我知道这意味着什么以及我可以做些什么来解决它。

1 个答案:

答案 0 :(得分:4)

你绝对可以做你想做的事情:

trait Positioned[T <: Positioned[T]] extends Ordered[T] {
  def position: Int = 1

  override def compare(that: T): Int = position - that.position
}

case class Image(id: String, override val position: Int = 1) extends Positioned[Image]

scala里面的REPL:

scala>  val imgs = Seq(Image("5", 5), Image("4", 4), Image("1", 1), Image("3", 3)) 
imgs: Seq[Image] = List(Image(5,5), Image(4,4),Image(1,1), Image(3,3))

scala>  imgs.sorted 
res1: Seq[Image] = List(Image(1,1), Image(3,3), Image(4,4), Image(5,5))