Variance is all about sub-typing. It tells us if a type constructor is a subtype of another type constructor. Variance defines inheritance relationshi

Scala Variances: Covariance, Contravariance, and Invariance

submited by
Style Pass
2021-07-12 13:30:04

Variance is all about sub-typing. It tells us if a type constructor is a subtype of another type constructor. Variance defines inheritance relationships of parameterized types(types that have parameters within them).

Every programming language supports the concept of types. Types give information about how to handle values at runtime. Subtyping adds more constraints to the values of a type.

Scala supports generic types or type constructors to reuse code for many types at once. Type constructors are a mechanism that provides type variables that we can bind to concrete types.

Scala supports variance annotations of type parameters of generic classes, to allow them to be covariant, contravariant, or invariant(if no annotations are used).

We defined the type constructor Shape as covariant, which means that the type Shape[Parallelogram] is a subtype of Shape[Polygon]. The covariance property allows us to declare a variable like:

Every time we need to assign a variable of type Shape[T], we can use an object of type Shape[R], given that R is a subtype of T.

Leave a Comment