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).
-
Covariance (+): Indicates that a parameterized type is covariant with respect to its type parameter. This means if
A
is a subtype ofB
, thenF[A]
is a subtype ofF[B]
, whereF
is a covariant type constructor. -
Contravariance (-): Indicates that a parameterized type is contravariant with respect to its type parameter. This means if
A
is a subtype ofB
, thenF[B]
is a subtype ofF[A]
, whereF
is a contravariant type constructor. -
Invariant (no annotation): Indicates no variance relationship between a parameterized type and its type parameter. This means
F[A]
andF[B]
are unrelated even ifA
is a subtype ofB
.
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:
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.