I just learned Scala. Now I am confused about Contravariance and Covariance.
From this page, I learned something below:
Covariance
Perhaps the most o
Variance is used to indicate subtyping in terms of Containers(eg: List
). In most of the languages, if a function requests object of Class Animal, passing any class that inherits Animal
(eg: Dog
) would be valid. However, in terms of Containers, these need not be valid.
If your function wants Container[A]
, what are the possible values that can be passed to it? If B
extends A
and passing Container[B]
is valid, then it is Covariant(eg: List[+T]
). If, A extends B(the inverse case) and passing Container[B]
for Container[A]
is valid, then it is Contravariant. Else, it is invariant(which is the default). You could refer to an article where I have tried explaining variances in Scala https://lakshmirajagopalan.github.io/variance-in-scala/.