Covariance & Contravariance & Variance
Given one parameterized type like List[T], with type A and B where A is a subclass of B, if List[A] is subclass of List[B], then we call it Covariance, else if List[B] is subclass of List[A], it's Contravariance. Type like List[T] which supports Covariance or Contravariance is called variance.
Covariant position & Contravariant position
Input below commands in scala terminal and see the output
Case 1:
class Test[+A] {def f(a: A){}} - - - - - - - - - - - - - - - -1
<console>:11: error: covariant type A occurs in contravariant position in type A of value a
Case 2:
class Test[-A] {def f(a: A){}} - - - - - - - - - - - - - - - -2
defined class Test
Case 3:
class Test[+A]{def f():A={...}} - - - - - - - - - - - - - - - -3
defined class Test
Case 4:
class Test[-A]{def f():A={...}} - - - - - - - - - - - - - - - -4
<console>:11:error: contravariant type A occurs in covariant position in type ()A of method f
Covariant position: position where defined the return type
Contravariant position: position where defined the arguments type
本文探讨了Scala中参数化类型如List[T]的协变和逆变概念。当A是B的子类时,如果List[A]是List[B]的子类,那么称为协变;反之,如果List[B]是List[A]的子类,则为逆变。在Scala终端中尝试不同的案例,可以看到协变位置(返回类型定义位置)和逆变位置(参数类型定义位置)的区别。

4541

被折叠的 条评论
为什么被折叠?



