协变
class Covariant[+T]{ }
对于两种类型 A 和 B,如果 A 是 B 的子类型,那么 Covariant[A] 就是 Covariant[B] 的子类型
逆变
class Inversion[-T]{ }
对于两种类型 A 和 B,如果 A 是 B 的子类型,那么 Inversion[B] 就是 Inversionr[A] 的子类型
不变
class Invariant[T]{ }
默认情况下,Scala中的泛型类是不变的
案例
package nj.zb.kb09.oop
object CovariantAndContravariant {
//协变点(Covariant)和逆变点(Inversion),不变(Invariant)
class Animal{
def eat():Unit={
println("动物要吃食物")
}
}
class Cat extends Animal{
override def eat(): Unit = println("猫要吃鱼")
}
class Tiger extends Cat{
override def eat(): Unit = println("老虎要吃肉")
}
//Factory[T] 不变
//Factory[Father] Factory[Son] 没有关系
//Factory[+T] 协变(儿子的公司是父亲公司的子公司)
//Factory[Father] Factory[Son]
//Factory[-T] 逆变(老虎是猫的子类,老虎的加工肉罐头公司是猫的加工鱼肉罐头公司的父类)
//Cat(吃鱼) <- Tiger(肉)
//Factory[Cat] -> Factory[Tiger]
//加工鱼肉罐头 加工肉罐头
class Invariant[T]{ //不变
}
class Covariant[+T]{ //协变
}
class Inversion[T]{ //逆变
}
def main(args: Array[String]): Unit = {
val cat = new Cat
val tiger = new Tiger
val cat2:Cat = tiger
//不变
val bubianCat:Invariant[Cat] = new Invariant[Cat]
val bubianTiger:Invariant[Tiger] = new Invariant[Tiger]
// 在泛型里不变的情况下 Invariant[T],Invariant[Cat]与Invariant[Tiger]没有任何变系
// val bubianCat2:Invariant[Cat] = bubianTiger //报错
//协变
val xiebianCat:Covariant[Cat] = new Covariant[Cat]
val xiebianTiger:Covariant[Tiger] = new Covariant[Tiger]
val xiebianCat2:Covariant[Cat] = xiebianTiger
//逆变
val nibianCat:Inversion[Cat] = new Inversion[Cat]
val nibianTiger:Inversion[Tiger] = new Inversion[Tiger]
val nibianTiger2:Inversion[Cat] = nibianCat
}
}