12-4 Ordered特质

  Ordered特质为你定义了<、>、<=和>=这些方法都是基于你提供的compare来实现的。因此,Ordered特质允许你只实现一个compare方法来增强某个类,让它拥有完整的比较操作。

object Rational{
  def main(args: Array[String]): Unit = {
    val half = new Rational(1, 2)
    val third = new Rational(1, 3)

    println(half < third)
    println(half > third)
  }
}

class Rational(n: Int, d: Int) extends Ordered[Rational]{

  require(d != 0)

  private val g = gcd(n.abs, d.abs)
  val numer: Int = n / g
  val denom: Int = d / g

  private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

  override def compare(that: Rational): Int = this.numer * that.denom - that.numer * this.denom

}

  

原文地址:https://www.cnblogs.com/noyouth/p/14092099.html