I have the following Scala class:
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 } }
to allow sorting by lastName, firstName and age.
How can I write this using pattern matching? I came up with the following, but is there a better way?
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 . Changed the use of Ordering[A]
according to Landei's answer:
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)
but it seems uncomfortable that I answer only second
. How can I make it more "elegant"?