scala学习之协变逆变入门(一)
+T 是协变,也就是子类的变化方向和父类一样
-T 是逆变,也就是子类的变化方向和父类相反
我的例子:
class Fruit[+T]
class Apple
class RedApple extends Apple
由此可以判断 Fruit[RedApple] 也是 Fruit[Apple] 的子类
class Fruit[-T] //逆变
class Apple
class RedApple extends Apple
由此可以判断 Fruit[RedApple] 也是 Fruit[Apple] 的父类
验证一下,
用 isInstanceOf 结果都是True....
网友回复如下:
isInstanceOf[T0]: BooleanTest whether the dynamic type of the receiver object is T0.Note that the result of the test is modulo Scala's erasure semantics. Therefore the expression 1.isInstanceOf[String] will return false, while the expression List(1).isInstanceOf[List[String]] will return true. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the specified type.
原来是泛型是被擦除的,所以其实比较的是Fruit[_].
然后我用 赋值去判断,因为子类可以替换父类出现的位置,据说是LSP原则
结果如下:
应该是验证了本文开头的两句话的。
转载于:https://blog.51cto.com/huanghongqiao/1053229