Subtyping and type parameters in Scala
Question
I'm new to Scala, and currently learning about type paramaters in Scala where I came across the following scenario.
Assume I have 2 classes A
and B
, where B
is a subtype of A
.
class A {
...
}
class B extends A {
...
}
So I can say B <: A
.
Does this also mean List[B] <: List[A]
?
La solution
In the case of List, it B <: A
does indeed imply List[B] <: List[A]
, because List's type parameter is covariant. Making a type parameter covariant means that it can only show up in covariant positions in the definition of List, i.e. it can only show up as the return type of a method, not as the type of a parameter. The "tour of Scala" contains a section about variance. Wikipedia also has a good article about variance. The three options for the variance of a type parameter are:
- invariance:
C[A]
is not a subtype ofC[B]
, no matter what the relationship betweenA
andB
is. Examples of this are mutable data structures such as arrays. - covariance:
B <: A
impliesC[B] <: C[A]
. Examples are immutable data structures or the return type of functions. - contravariance:
A <: B
impliesC[B] <: C[A]
. For example, Functions are contravariant in the types of their parameters.