1. 程式人生 > >scala進階20-隱式轉換至Ordered與Ordering

scala進階20-隱式轉換至Ordered與Ordering

//Ordering是Ordering[T]隱式值
class Pair_Implicits[T: Ordering](val first: T, val second: T) {
  def bigger(implicit ordered: Ordering[T]) = {
    if (ordered.compare(first, second) > 0) first else second
  }
}

//也可以通過implicitly來實現
class Pair_Implicity[T: Ordering](val first: T, val second: T) {
  def bigger = if (implicitly[Ordering[T]].compare(first, second) > 0) first else second
}

class Pair_Implicitly_Odereded[T: Ordering](val first: T, val second: T) {
  def bigger = {
    import Ordered._//隱式將Ordering轉換為Ordered
    if (first > second) first else second
  }
}

object Context_Bounds_Internals {
  def main(args: Array[String]): Unit = {
    println(new Pair_Implicits(7, 9).bigger)
    println(new Pair_Implicity(7, 9).bigger)
    println(new Pair_Implicitly_Odereded(7, 9).bigger)
  }
}