在Scala中将模式匹配用于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
}
}
允许按lastName,firstName和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
}
}
}
更新:根据Landei的答案更改为使用Ordering[A]
:
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
似乎很尴尬。如何使其更“优雅”?
没有找到相关结果
已邀请:
1 个回复
蹄渭信妥扳
s,它们不能保证为-1,0,1。Haskell's解决方案可以返回“枚举”对象(LT, EQ,GT)更清晰,可与模式匹配,但出于兼容性原因,Scala似乎遵循了C ++ / Java传统。 当然,您可以推出自己的比较“框架”:
您可以写: