爲Ordered.compare匹配,我有以下的Scala類:使用模式在斯卡拉
case class Person(firstName: String, lastName: String, age: Int)
extends Ordered[Person] {
def compare(that: Person): Int = {
if (this.lastName < that.lastName) -1
else if (this.lastName > that.lastName) 1
else if (this.firstName < that.firstName) -1
else if (this.firstName > that.firstName) 1
else this.age compare that.age
}
}
允許通過姓氏,名字,和年齡排序。
如何使用模式匹配來編寫此代碼?我已經提出了以下內容,但有沒有更好的方法?
case class Person(firstName: String, lastName: String, age: Int)
extends Ordered[Person] {
def compare(that: Person): Int = {
that match {
case Person(_, thatLastName, _) if this.lastName < thatFile => -1
case Person(_, thatLastName, _) if this.lastName > thatFile => 1
case Person(thatFirstName, _, _) if this.firstName < thatFirstName => -1
case Person(thatFirstName, _, _) if this.firstName > thatFirstName => 1
case Person(_, _, thatAge) => this.age compare thatAge
}
}
}
UPDATE:改爲使用Ordering[A]
按照Landei的回答是:
implicit val personOrdering = new Ordering[Person] {
def compare(first: Person, second:Person): Int = {
second match {
case Person(_, thatLastName, _) if first.lastName < thatLastName => -1
case Person(_, thatLastName, _) if first.lastName > thatLastName => 1
case Person(thatFirstName, _, _) if first.firstName < thatFirstName => -1
case Person(thatFirstName, _, _) if first.firstName > thatFirstName => 1
case Person(_, _, thatAge) => first.age compare thatAge
}
}
}
case class Person(firstName: String, lastName: String, age: Int)
但似乎尷尬,我只匹配second
。我怎樣才能讓它更「優雅」?
對我來說,更好的辦法顯然是無圖案在此匹配案例... – 2011-04-19 11:32:55
@ Jean-Philippe Pellet:但是當你需要排列更多列時會發生什麼?我認爲(希望)模式匹配版本更具可讀性,也許稍微使用空格(請參閱更新)。 – Ralph 2011-04-19 11:34:47