选项 1:排序依据
使用该sortBy
方法,这可能非常简单:
case class Person(first: String, middle: String, last: String)
val personList = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))
personList.sortBy{ case Person(f,m,l) => (l,f,m) }
选项 2:扩展 Ordered[Person]
通过扩展Ordered[Person]
,该类将知道如何对自己进行排序,因此我们可以免费获得sorted
、min
和之类的东西max
:
case class Person(first: String, middle: String, last: String) extends Ordered[Person] {
def compare(that: Person): Int =
(last compare that.last) match {
case 0 =>
(first compare that.first) match {
case 0 => middle compare that.middle
case c => c
}
case c => c
}
}
val personList = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))
personList.sorted
personList.min
personList.max
选项 3:隐式排序
如果您使用隐含的Ordering
, ,那么您会得到sorted
,min
等,而不会将该特定顺序绑定到您的原始类。这种解耦可能很方便,也可能很烦人,具体取决于您的具体情况。
case class Person(first: String, middle: String, last: String)
implicit val ord = new Ordering[Person] {
def compare(self: Person, that: Person): Int =
(self.last compare that.last) match {
case 0 =>
(self.first compare that.first) match {
case 0 => self.middle compare that.middle
case c => c
}
case c => c
}
}
val personList = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))
personList.sorted
personList.min
personList.max