Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtyping and type parameters in Scala

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]?

like image 255
Raj Avatar asked Oct 14 '12 10:10

Raj


1 Answers

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 of C[B], no matter what the relationship between A and B is. Examples of this are mutable data structures such as arrays.
  • covariance: B <: A implies C[B] <: C[A]. Examples are immutable data structures or the return type of functions.
  • contravariance: A <: B implies C[B] <: C[A]. For example, Functions are contravariant in the types of their parameters.
like image 151
Kim Stebel Avatar answered Nov 15 '22 05:11

Kim Stebel