top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Variant, Invariant, Covariant and Contravariant in Scala?

+2 votes
401 views
What is Variant, Invariant, Covariant and Contravariant in Scala?
posted Aug 3, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Variance

Variance defines Inheritance relationships of Parameterized Types. Variance is all about Sub-Typing.

Advantage of Variance in Scala

The main advantage of Scala Variance is:

Variance makes Scala collections more Type-Safe.

Variance gives more flexible development.

Scala Variance gives us a technique to develop Reliable Applications.

Types of Variance in Scala

Scala supports the following three kinds of Variance.

Covariant

Invariant

Contravariant

Scala Covariance Syntax:

To represent Covariance relationship between two Parameterized Types, Scala uses the following syntax:
Prefixing Type Parameter with “+” symbol defines Covariance in Scala.

If we remove Variance Annotation in Animal class definition, like as shown below:

 class Animal[T](val animial:T)

It wont compile. We will get the following compilation error message:

Type mismatch, expected: Animal[Dog], found: Animal[Puppy]

To solve these kind of problems, we should use Scala Covariance.

As per this example, we can say the following Scala Covariance:

“As Puppy is subtype of Dog, Animal[Puppy] is a subtype of Animal[Dog]. We can use Animal[Puppy] where we require Animal[Dog].” This is know as Scala Covariance.

Invariant in Scala

If “S” is subtype of “T” then List[S] and List[T] don’t have Inheritance Relationship or Sub-Typing. That means both are unrelated.

This kind of Relationship between two Parameterized Types is known as “Invariant or Non-Variant”

In Scala, by default Generic Types have Non-Variant relationship. If we define Parameterized Types without using “+’ or “-” symbols, then they are known as Invariants.

What is Variance Annotation in Scala?

Variance Annotation means defining “+” or “-” before Type Parameters.

Example:

+T and – T are know as Variance Annotations in Scala.

answer Sep 14, 2016 by Joy Nelson
...