首先定义一个类 A,其参数类型 T 为协变,类中包含一个方法 func,该方法有一个类型为 T 的参数:html
1 class A[+T] { 2 def func(x: T) {} 3 }
此时在 x 处会有异常提示,covariant type T occurs in contravariant position in type T of value xweb
val father: A[AnyRef] = null.asInstanceOf[A[AnyRef]] // 父类对象,包含方法 func(x: AnyRef) val child: A[String] = null.asInstanceOf[A[String]] // 子类对象,包含方法 func(x: String)
1 def otherFunc(x: A[AnyRef]): Unit = { 2 x.func(Nil) 3 }
1 val fatherFather: A[Any] = null.asInstanceOf[A[Any]] // func(x: Any) 2 otherFunc(fatherFather)// 若是 T 为协变,此处会提示异常
1 class B[+T] { 2 def func(): T = { 3 null.asInstanceOf[T] 4 } 5 } 6 // 与 Function0[+A] 等价
1 class A[-T] { 2 def func(x: T) {} 3 } 4 // 与 Function1[-A, Unit] 等价 5 6 val father: A[AnyRef] = null.asInstanceOf[A[AnyRef]] // func(x: AnyRef) 7 val fatherFather: A[Any] = null.asInstanceOf[A[Any]] // func(x: Any) 8 9 def otherFunc(x: A[AnyRef]): Unit = { 10 x.func(Nil) 11 } 12 13 otherFunc(father) // success 14 otherFunc(fatherFather)// success