scala通过实现trait Ordered[T]定义一个可排序的类

编写一个类,可按照人名排序,先按lastName排序,再按firstName排序,继承Ordered

class Person(val firstName: String, val lastName: String) extends Ordered[Person] {
  override def compare(that: Person): Int = {
    val lastNameComparison = lastName.compareToIgnoreCase(that.lastName)
    if (lastNameComparison != 0)
      lastNameComparison
    else
      firstName.compareToIgnoreCase(that.firstName)
  }
  
}


你可能感兴趣的:(scala通过实现trait Ordered[T]定义一个可排序的类)