Scala型变
- 协变
class Foo[+T] // 协变类
对于两种类型 A 和 B,如果 A 是 B 的子类型,那么 Foo[A] 就是 Foo[B] 的子类型
- 逆变
class Bar[-T] // 逆变类
对于两种类型 A 和 B,如果 A 是 B 的子类型,那么 Bar[B] 就是 Bar[A] 的子类型
- 不变
class Baz[T] // 不变类
默认情况下,Scala中的泛型类是不变的
- 案例
object CovarianAndContravariant {
//协变点(Convariant)和逆变点(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("老虎吃肉")
}
//Father Son
//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 = new Tiger
val niCat:Inversion[Cat]=new Inversion[Cat]
val niTiger:Inversion[Tiger]=new Inversion[Tiger]
val niTiger2:Inversion[Tiger]=niCat
val xieCat:Covariant[Cat]=new Covariant[Cat]
val xieTiger:Covariant[Tiger]=new Covariant[Tiger]
val xieCat2:Covariant[Cat]=xieTiger
val bubian:Invariant[Cat] = new Invariant[Cat]
val bubianTiger:Invariant[Tiger] = new Invariant[Tiger]
// val bubianCat2:Invariant[Cat] = bubianTiger
// 报错 在泛型里不变的情况下
// Invariant[T],Invariant[Cat],new Invariant[Tiger]没有任何变细
}