# Scala Ordered Trait

2018-09-28 18:18 更新

## Ordered Trait

``````class Rational (n:Int, d:Int) {
...
def < (that:Rational) =     this.numer * that.denom  > that.numer * this.denom
def > (that:Rational) = that < this
def <=(that:Rational) = (this < that) || (this == that)   def >=(that:Rational) = (this  > that) || (this == that)
}``````

Scala 对于比较这种常见的操作，提供了 Ordered Trait 定义，使用它，你可以把所有的比较运算的代码使用一个 compare 定义来替代。这个 ordered trait 可以让需要实现比较运算的类，通过和 Ordered 特质“融合”，而只需实现一个 compare 方法即可。

``````class Rational (n:Int, d:Int) extends Ordered[Rational]{
...
override def compare (that:Rational)=
(this.numer*that.denom)-(that.numer*that.denom)
}``````

``````scala> class Rational (n:Int, d:Int) extends Ordered[Rational]{
|   require(d!=0)
|   private val g =gcd (n.abs,d.abs)
|   val numer =n/g
|   val denom =d/g
|   override def toString = numer + "/" +denom
|   def +(that:Rational)  =
|     new Rational(
|       numer * that.denom + that.numer* denom,
|       denom * that.denom
|     )
|   def * (that:Rational) =
|     new Rational( numer * that.numer, denom * that.denom)
|   def this(n:Int) = this(n,1)
|   private def gcd(a:Int,b:Int):Int =
|     if(b==0) a else gcd(b, a % b)
|
|   override def compare (that:Rational)=
|     (this.numer*that.denom)-(that.numer*that.denom)
|
| }
defined class Rational
scala> val half =new Rational(1,2)
half: Rational = 1/2
scala>   val third=new Rational(1,3)
third: Rational = 1/3
scala> half < third res0: Boolean = false
scala> half >= third
res1: Boolean = true``````

App下载