Friday, April 24, 2015

Comparing covariance/contravariance rules in C#, Java and Scala

Different programming languages support variance (covariance/contravariance) in different ways. My goal is to compare all supported types of variance in C#, Java and Scala, and to reason about why some architectural decisions have been made by language designers.

Arrays covariance+
(unsafe at runtime)
(unsafe at runtime)

(arrays are invariant by design)
Though, there is support for Java's "covariant" arrays, of course.
Arrays contravariance___
Generics variance

Defined by a generic type creator (definition-site).
(Restricted to generic interfaces and generic delegates)

Defined by clients of generic type using wildcards (use-site).

Defined by a generic type creator (definition-site).
Also, there are existential types that cover Java's wildcards functionality.
Overriding: return type covariance_++
Overriding: parameter type contravariance___

No comments:

Post a Comment