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 <: 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:
C[A]
is not a subtype of C[B]
, no matter what the relationship between A
and B
is. Examples of this are mutable data structures such as arrays.B <: A
implies C[B] <: C[A]
. Examples are immutable data structures or the return type of functions.A <: B
implies C[B] <: C[A]
. For example, Functions are contravariant in the types of their parameters.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With