我正在嘗試爲不同但相似類別的對象定義自然排序。在Java中,我將使用Comparable
,看起來在Scala中執行等效的方法是使用Ordered
。我有以下特點:Scala中的有序特徵的問題
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
請讓我知道這意味着什麼和我能做什麼來解決它。
也許這與[SI-8541(https://開頭issues.scala-lang.org/browse/SI-8541)? – 2014-10-19 02:02:29
我也看到了,很可能。但由於案件有些差異可能很大,我仍然認爲我會問。有了Scala的所有編譯魔法,我很難找出問題所在。 – Vidya 2014-10-19 02:29:24
順便說一句,略有偏離主題,但如果有任何溢出的機會,在比較方法中減法是不正確的。返回'position.compare(that.position)'會更安全,速度稍慢。 – Nate 2014-10-21 02:44:06