18.5 上下文界定

与 view bounds 一样 context bounds(上下文界定)也是隐式参数的语法糖。为语法上的方便, 引入了"上下文界定"这个概念

语法:

T:M

其中, M是另外一个泛型类. 他要求作用域中必须存在一个类型为M[T]的隐式值.

案例1:

object ContextBoundDemo {
    def main(args: Array[String]): Unit = {
        val pair = new Pair(1,2)
        println(pair.smaller)
    }
}

class Pair[T:Ordering](first: T, second: T){
    def smaller(implicit ord: Ordering[T]) ={
        if (ord.lt(first, second)) first else second
    }
}

说明

  • 我们new Pair(1,2)的时候, Scala 会推断出TInt, 由于Predef作用域中存在一个类型为Ordering[Int]的隐式值, 因此Int满足上下文界定. 这个Ordering[Int]类型的值就会传入需要该值的方法当中.

  • 如果你愿意, 也可以获取这个隐式值(通过Predef对象的implicitly方法):

    def smaller =
          // 从冥界召唤隐式值
          if (implicitly[Ordering[T]].lt(first, second)) first else second
    

案例2:

package Generic

import scala.runtime.RichInt

object GenericDemo1 {

    implicit val ord: Ordering[User] = new Ordering[User] {
        override def compare(x: User, y: User): Int = x.age - y.age
    }

    def main(args: Array[String]): Unit = {
        val pair = new Pair(new User(10), new User(20))
        println(pair.smaller)
    }
}

class User(val age: Int) {
    override def toString: String = s"age = $age"
}

class Pair[T: Ordering](val first: T, val second: T) {
    def smaller(implicit ord: Ordering[T]): T = {
        if (ord.compare(first, second) < 0)
            first
        else
            second
    }
}
Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-03-03 21:15:44

results matching ""

    No results matching ""