scala的convariant(協變)和contravariant(逆變)

class Cell[T](init:T){
  private[this] var current = init
  def get = current
  def set(x:T) = current = x
}
object ConvariantTest {
  def main(args: Array[String]): Unit = {
    val c1 = new Cell("abc")
    val c2:Cell[Any] = c1 //提示有錯誤
    c2.set(1)

  }
}

在語句val c2:Cell[Any] = c1這一句中出現錯誤:html

Error:(9, 24) type mismatch;
 found   : Cell[String]
 required: Cell[Any]
Note: String <: Any, but class Cell is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
    val c2:Cell[Any] = c1

 

 

在網頁 http://www.cnblogs.com/fxjwind/p/3480462.html 中還有些其它介紹。ui

相關文章
相關標籤/搜索