scala的視圖界定

上一篇幀子的代碼中,若是main函數中不是用字符串而是用數字則程序不能正常編譯:java

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)
  }
}

此時就須要用到視圖界定了,將代碼改成:app

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中:.net

@inline implicit def intWrapper(x: Int)         = new runtime.RichInt(x)

而RichInt.scala中:scala

final class RichInt(val self: Int) extends AnyVal with ScalaNumberProxy[Int] with RangedProxy[Int]

而ScalaNumberProxy.scala中:code

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中:blog

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],固然是知足視圖界定要求的。接口

相關文章
相關標籤/搜索