Type Systems: Covariance, Contravariance, Bivariance, and Invariance explained
source link: https://www.tuicool.com/articles/hit/qmeyae2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Please do not link to this article on Reddit or Hacker News.
Variance is a topic that comes up fairly often in type systems and can be a bit confusing the first time you hear it. Let’s walk through each form of variance.
First we’ll setup a couple of classes that extend one another.
class Noun {}
class City extends Noun {}
class SanFrancisco extends City {}
We’ll use these classes to write a method that has each kind of variance.
Invariance
function method(value: <strong><em>Invariant</em><City></strong>) {...}
method(new Noun()); // error...
method(new City()); // okay
method(new SanFrancisco()); // error...
Invariance does not accept supertypes .
Invariance does not accept subtypes .
Covariance
function method(value: <strong><em>Covariant</em><City></strong>) {...}
method(new Noun()); // error...
method(new City()); // okay
method(new SanFrancisco()); // okay
Covariance does not accept supertypes .
Covariance does accept subtypes .
Contravariance
function method(value: <strong><em>Contravariant</em><City></strong>) {...}
method(new Noun()); // okay
method(new City()); // okay
method(new SanFrancisco()); // error...
Contravariance does accept supertypes .
Contravariance does not accept subtypes .
Bivariance
function method(value: <strong><em>Bivariant</em><City></strong>) {...}
method(new Noun()); // okay
method(new City()); // okay
method(new SanFrancisco()); // okay
Bivariance does accept supertypes .
Bivariance does accept subtypes .
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK