Saturday, September 24, 2016

'Ordered' trait : Example...

scala> ////////////////////////////////////////////

scala> //  A Class without 'Ordered' trait #264

scala> ////////////////////////////////////////////

scala> class Temperature(val temp: Double) {
     |   def < (that: Temperature): Boolean = {
     |     println("Comparing : <")
     |     this.temp < that.temp
     |   }
     |   def > (that: Temperature) = {
     |     println("Comparing : >")
     |     that < this
     |   }
     |   def <= (that: Temperature) = {
     |     println("Comparing : <=")
     |     (this < that) || (this == that)
     |   }
     |   def >= (that: Temperature) = {
     |     println("Comparing : >=")
     |     (this > that) || (this == that)
     |   }
     | }
defined class Temperature

scala>

scala> val t1 = new Temperature(90.5)
t1: Temperature = Temperature@1e90062d

scala> val t2 = new Temperature(80.5)
t2: Temperature = Temperature@17806b85

scala>

scala> t1 > t2
Comparing : >
Comparing : <
res91: Boolean = true

scala> t1 >= t2
Comparing : >=
Comparing : >
Comparing : <
res92: Boolean = true

scala> t1 < t2
Comparing : <
res93: Boolean = false

scala> t1 == t2
res94: Boolean = false

scala>

scala> ////////////////////////////////////////////

scala> //  A Class with 'Ordered' trait #264

scala> ////////////////////////////////////////////

scala> class Temperature(val temp: Double) extends Ordered[Temperature]{
     |   def compare(that: Temperature) = {
     |       val res = this.temp - that.temp
     |       if(res == 0) {
     |         0
     |       }else if(res < 0) {
     |         -1
     |       }else{
     |         1
     |       }
     |   }
     | }
defined class Temperature

scala> val t1 = new Temperature(90.5)
t1: Temperature = Temperature@1512113f

scala> val t2 = new Temperature(80.5)
t2: Temperature = Temperature@6cba4b01

scala>

scala> t1 > t2
res95: Boolean = true

scala> t1 >= t2
res96: Boolean = true

scala> t1 < t2
res97: Boolean = false

scala> t1 == t2
res98: Boolean = false