Scala – Variance

  • date 18th February, 2021 |
  • by Prwatech |
  • 0 Comments

Variances | Tour of Scala

 

Variance

Variance is the correlation between the subtyping relationships of complex types and the subtyping relationships of their component types.

 

In Scala, variances are a key concept use to define the relationship between types in the context of subtyping and generics. Variances specify how subtyping of parameterized types (generics) relates to subtyping of their type parameters.

Scala supports three variance annotations: + (covariant), - (contravariant), and no annotation (invariant).

  1. Covariance (+): Indicates that a parameterized type is covariant with respect to its type parameter. This means if A is a subtype of B, then F[A] is a subtype of F[B], where F is a covariant type constructor.

  2. Contravariance (-): Indicates that a parameterized type is contravariant with respect to its type parameter. This means if A is a subtype of B, then F[B] is a subtype of F[A], where F is a contravariant type constructor.

  3. Invariant (no annotation): Indicates no variance relationship between a parameterized type and its type parameter. This means F[A] and F[B] are unrelated even if A is a subtype of B.

Covariance

A type parameter T of a generic class can be made covariant by using the annotation +T.

Here is the program for your reference:

This image has an empty alt attribute; its file name is Screenshot-506.png

 

Contravariance

A type parameter A of a generic class can contravariant by using the annotation -A.

Invariance

Generic classes in Scala are invariant by default.

 

Quick Support

image image