-6
特徵有序[A]在Scala中的含義是什麼?它的目的是什麼? 我的理解是關係到東西訂貨字符串。請幫助Scala中的有序性[A]的含義是什麼?它的目的是什麼?
特徵有序[A]在Scala中的含義是什麼?它的目的是什麼? 我的理解是關係到東西訂貨字符串。請幫助Scala中的有序性[A]的含義是什麼?它的目的是什麼?
爲Ordered[A]
的文檔是非常簡單的:
/** A trait for data that have a single, natural ordering. See
* [[scala.math.Ordering]] before using this trait for
* more information about whether to use [[scala.math.Ordering]] instead.
*
* Classes that implement this trait can be sorted with
* [[scala.util.Sorting]] and can be compared with standard comparison operators
* (e.g. > and <).
*
* Ordered should be used for data with a single, natural ordering (like
* integers) while Ordering allows for multiple ordering implementations.
* An Ordering instance will be implicitly created if necessary.
它可以讓你表達你的類型的整體排序。所有你需要做的是落實compare
方法:
case class Foo(id: Int) extends Ordered[Foo] {
override def compare(that: Foo): Int = that.id match {
case x if x < id => 1
case x if x > id => -1
case _ => 0
}
}
然後你就可以使用需要您提供訂單的方法。例如,sorted
:
def main(args: Array[String]): Unit = {
println(List(Foo(2), Foo(1), Foo(3)).sorted)
}
注意,雖然sorted
需要Ordering[A]
,存在Ordered[A]
< =>Ordering[A]
之間的隱式轉換http://www.scala-lang.org/api/current/斯卡拉/數學/ Ordered.html – avysk