Scala | Variances
Variance is the interconnection of Sub-Typing relationships which are either of complicated types or of their constituent types. Variance explains inheritance correlation of Types that have parameters or arguments within them. These types belongs to the generic classes, which takes a type like a parameter. In the presence of Variance one can create relations between complicated types and in its absence we won’t be able to reiterate the abstraction class. The Scala Variances are of three types, which are as follows:
- Covariant
- Contravariant
- Invariant
Some important points:
- In Scala collection’s types can be constructed more securely through Variances.
- Variances can provide us with some extra adjustable advancements.
- It also helps in the development of authentic applications.
- Variances can be applied on any Scala Types like List, Sets, etc.
Let’s discuss each type in detail.
- Covariant: If a generic class has a type parameter T, then its Covariant notation will be [+T]. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T, then you can say that List[S] is also the sub-type of List[T]. If two types are related like this then they fall under the Covariant type. List[T] can be called as Generic.
Syntax:List[+T]
Here, T is the type parameter and + is the symbol of Covariance.
Example:// Scala program of covariant// type// Creating an abstract class// for StudentabstractclassStudent{defname:String}// Creating a sub-class Girls// of StudentcaseclassGirls(name:String)extendsStudent// Creating a sub-class Boys// of StudentcaseclassBoys(name:String)extendsStudent// Creating an Object Covariance// that inherits main method of// AppobjectCovarianceextendsApp{// Creating a methoddefStudentnames(students:List[Student]):Unit={students.foreach { student=>// Displays students nameprintln(student.name)}}// Assigning namesvalboys:List[Boys]=List(Boys("Kanchan"), Boys("Rahul"))valgirls:List[Girls]=List(Girls("Nidhi"), Girls("Geeta"))// Accessing list of boysStudentnames(boys)// Accessing list of girlsStudentnames(girls)}chevron_rightfilter_noneOutput:Kanchan Rahul Nidhi Geeta
Here, List of boys and girls both belongs to the List of students as they are its sub-type and so, here names of all the students are displayed when the Super-type Student is called.
Note:- Abstract class is utilized here to apply covariance as it has List[+T] with it where, the type parameter T is covariant.
- A trait App is used here to speedily change objects into workable programs.
- Contravariant: If a generic class has a type parameter T, then its Contravariant notation will be [-T]. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T, but List[T] is the sub-type of List[S]. If two types are related like this then they fall under the Contravariant type. It is opposite of covariant.
Syntax:List[-T]
Here, T is the type parameter and – is the symbol of Contravariance.
Example:// Scala program of Variance of// Contravariant type// abstract class with a contravariant// type parameterabstractclassShow[-T]{// Method for printing// type Tdefprint(value:T):Unit}// A class structureabstractclassVehicle{defname:String}// Creating sub-class of VehiclecaseclassCar(name:String)extendsVehicle// Creating sub-class of class// ShowclassVehicleShowextendsShow[Vehicle]{defprint(vehicle:Vehicle):Unit=// Displays name of the vehicleprintln("The name of the vehicle is: "+ vehicle.name)}// Creating sub-class of class// ShowclassCarShowextendsShow[Car]{defprint(car:Car):Unit=// Displays name of the carprintln("The name of the car is: "+ car.name)}// Inheriting main method of// the trait AppobjectContravarianceextendsApp{// Assigning value to the namevalnewCar:Car=Car("Scorpio")// Defining a method that// prints the namedefprintnewCar(show:Show[Car]):Unit={show.print(newCar)}// Creating objectsvalshowcar:Show[Car]=newCarShowvalshowvehicle:Show[Vehicle]=newVehicleShow// Accessing nameprintnewCar(showcar)printnewCar(showvehicle)}chevron_rightfilter_noneOutput:The name of the car is: Scorpio The name of the vehicle is: Scorpio
It is Contravariant so, we are able to substitute Show[Vehicle] for Show[Car] and that’s why both vehicle and car returns the same name.
- Invariant: In Scala, generic types are by default invariant. Suppose, we have two List types of Scala i.e, S and T. where, S is sub-type of T but List[T] and List[S] are not at all related, then they fall under the invariant type.
Syntax:List[T]
Here, we don’t use any symbol for invariant relationship.
Note: The classes like Array[T], ListBuffer[T], ArrayBuffer[T] etc. are mutable so, they have invariant type parameter, if we use invariant type parameters in inheritance relationship or sub-typing then we will get a compilation error.
Recommended Posts:
- Scala | Either
- Set in Scala | Set-1
- Set in Scala | Set-2
- Scala Map
- Scala Int %(x: Int) method with example
- Scala Set sum() method with example
- Scala Set min() method with example
- HashSet In Scala
- Scala | REPL
- BitSet in Scala
- Scala Set take() method with example
- Scala | Traits
- Scala Stream
- Hello World in Scala
- Scala | Value Classes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



