2017-02-26 80 views

回答

2

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]