Variance of Functions, Containers, and References
Derive covariance and contravariance from substitutability and see why read–write containers generally permit neither direction.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 2
- Reading time
- 1 min
In this article2 chapters
Consumers can accept broader input
Suppose \(S\) is a subtype of \(T\). A function accepting every \(T\) is safe where a function accepting \(S\) is expected. Function input is therefore contravariant. A returned \(S\) is safe where a \(T\) result is required, making output covariant. For function subtyping, compare the input type in reverse and the result type in the ordinary direction. This captures the obligations of a caller and a callee independently.
Mutability combines opposite roles
A read-only container of \(S\) can provide values as \(T\). A writer accepting arbitrary \(T\) must be able to store those values. A read–write cell promises both operations, so treating a cell of \(S\) as a cell of \(T\) could allow a write that the original cell cannot promise to hold. Algebraic data types show read-only product and sum structure. Ownership and borrowing examine restrictions on mutation and shared access.[1][2]