Sunrabbit

Covariance and Contravariance

Created: 2024-11-01

Created: 2024-11-01 01:06

This content is something you'll naturally encounter if you're a compiler developer,
use compiler APIs,
or overuse a compiler's type system.

It's something that naturally integrates into our coding lives.


Simply put, if we have two types, Animal and Dog,

if a Dog can be assigned to an Animal, it's calledcovarianceand

conversely,if an Animal can be assigned to a Dog, it's calledcontravariance.

Generally, you can't assign an Animal to a Dog.

This is because, from a general perspective, it's not logical,
so compiler developers are mindful of this and implementonly in certain partscontravariance.


Usually, contravariance is implemented for function input values, while covariance is maintained for output values.


You might wonderwhy this contravariance is necessary.

It helps in areas like event handling to maintain greater flexibility and polymorphism.

Covariance can sometimes cause problems.


In the above code, we've used Animal where Dog would normally go, ensuring flexibility and allowing us to consider polymorphism.

However, if a subtype of Dog like Chiwawa were used instead of Animal, an error would occur when executing the event handler because Dog does not have the Chiwawa-specific interfaces.


When executing the function, we can use the Animal type, and the code will handle Animal subtypes automatically.

This might give the impression that a Dog is assigned to an Animal.


As such, contravariance is usually used for input values.


Invariance and Invariance


Briefly, invariance is both covariance and contravariance, while invariance is neither.

In Conclusion

This topic is simple if understood simply, and complex if delved into deeply, so

I recommend reading this as well.




Comments0