Understanding different kinds of variance

There are four different kinds of variance as described in computer science literature. We will first describe them in a formal manner first and then come back to do more hands-on exercises to reinforce our understanding. 

Given that S is a subtype of T, there are four different ways to reason about the relationship between parametric types P{S} and P{T}:

  • Covariant: P{S} is a subtype of P{T} (co here means the same direction)
  • Contravariant: P{T} is a subtype of P{S} (contra here means the opposite direction)
  • Invariant: neither covariant nor contravariant
  • Bivariant: both covariant and contravariant

When do we find variance useful? Perhaps not too surprisingly, variance is a key ingredient whenever multiple dispatch come into action. Based on the Liskov substitution principle, the language runtime must figure out whether the object being passed is a subtype of the method argument before dispatching to the method.

Interestingly, variance is one thing that often diverges between different programming languages. Sometimes, there are historical reasons for this, and sometimes it depends on the target use cases for the language. In the next few sections, we will explore the topic from several angles. We will start with parametric types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.132