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

相关文章
相关标签/搜索