Contravariance vs Covariance in Scala

后端 未结 3 641
無奈伤痛
無奈伤痛 2020-12-05 05:40

I just learned Scala. Now I am confused about Contravariance and Covariance.

From this page, I learned something below:

Covariance

Perhaps the most o

3条回答
  •  独厮守ぢ
    2020-12-05 06:39

    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/.

提交回复
热议问题