大数据之scala高级语法学习
协变
案例一:
class Animal {} class Bird extends Animal {} class Animal {} class Bird extends Animal {} //协变 class Covariant[T](t:T){} val cov = new Covariant[Bird](new Bird) val cov2:Covariant[Animal] = cov
c不能赋值给c2,因为Covariant定义成不变类型。
稍微改一下:
class Animal {} class Bird extends Animal {} class Animal {} class Bird extends Animal {} //协变 class Covariant[+T](t:T){} val cov = new Covariant[Bird](new Bird) val cov2:Covariant[Animal] = cov
因为Consumer定义成协变类型的,所以Covariant[Bird]是Covariant[Animal]的子类型,所以它可以被赋值给c2。
Scala的逆变:
class Animal {} class Bird extends Animal {} class Contravariant[-T](t: T) { } val c: Contravariant[Animal] = new Contravariant[Animal](new Animal) val c2: Contravariant[Bird] = c
这里Consumer[-T]定义成逆变类型,所以Contravariant[Animal]被看作Contravariant[Animal]的子类型,故c可以被赋值给c2。