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]?
In the case of List, it
B <: Adoes indeed implyList[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:C[A]is not a subtype ofC[B], no matter what the relationship betweenAandBis. Examples of this are mutable data structures such as arrays.B <: AimpliesC[B] <: C[A]. Examples are immutable data structures or the return type of functions.A <: BimpliesC[B] <: C[A]. For example, Functions are contravariant in the types of their parameters.