在帧子的代码中,如果main函数中不是用字符串而是用数字则程序不能正常编译:
class Pair[T <: Comparable[T]](val first:T,val second:T) //类型T必须要是Comparable接口的子类(即T是Comparable的下界){ def bigger = if(first.compareTo(second) > 0) first else second}class Pair_Lower_Bound[T](val first:T,val second:T){ def replaceFirst[R >: T](newFirst:R) = new Pair_Lower_Bound(newFirst,second) //类型R是T类型的父类(也即R是T的上界)}object Type_Variables_BoundsTest { def main(args: Array[String]): Unit = { val pair = new Pair(2,3) //此处代码不能正常编译 println(pair.bigger) }}
此时就需要用到视图界定了,将代码改为:
class VBPair[T <% Comparable[T]](val first:T,val second:T) //T类型可以隐式转换成Comparable[T]类型{ def bigger = if(first.compareTo(second) > 0) first else second}
则val pair =new VBPair(2,3)就能成功了。这是因为Int可以隐式转换成RichInt,具体分析通过源码可以看到:
predef.scala中:
@inline implicit def intWrapper(x: Int) = new runtime.RichInt(x)
而RichInt.scala中:
final class RichInt(val self: Int) extends AnyVal with ScalaNumberProxy[Int] with RangedProxy[Int]
而ScalaNumberProxy.scala中:
trait ScalaNumberProxy[T] extends Any with ScalaNumericAnyConversions with Typed[T] with OrderedProxy[T]
trait OrderedProxy[T] extends Any with Ordered[T] with Typed[T]
而package.scala中:
type Ordered[T] = scala.math.Ordered[T]
而Ordered.scala中:
trait Ordered[A] extends Any with java.lang.Comparable[A]
所以说,当用2和3调用的时候, 首先int转换成RichInt,而RichInt最终继承至Comparable[Int],当然是满足视图界定要求的。