Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the two sentences about "Covariance" and "Contravariance"?

I'm reading the first section of "Scala in depth", there are two sentences in the first section about "covariance" and "contrvariance":

Covariance (+T or ? extends T) is when a type can be coerced down the inheritance hierarchy.

Contravariance(-T or ? super T) is when a type can be coerced up the inheritance hierarchy.

I have read some documents about "Covariance" and "Contravariance", but I can't understand the word "coerced down" and "coerced up" here in this context.

like image 864
Freewind Avatar asked Dec 16 '22 03:12

Freewind


1 Answers

[TOP / ABSTRACT]

Thing
  ↓
Animal
  ↓
Human
  ↓
Programmer
  ↓
Scala Dev

[BOTTOM / SPECIFIC]

Covariance: Accept T or lower.
I asked for a [+Human], I will accept any of these: [Human, Programmer, Scala Dev].

Contravariance: Accept T or higher.
I asked for a [-Human], I will accept any of these: [Thing, Animal, Human].

Inariance: Accept T and only T.

Coercion.
Coercing a type up/down the type hierarchy means checking that a type's super/sub type passes type constraints. For example, a covariant function needs a Human but we've only got a Programmer, that's ok, the compiler can coerce the Programmer into Human to satisfy typing constraints.

like image 191
Golly Avatar answered May 16 '23 09:05

Golly