-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