Updated April 20, 2023
Definition of Scala Generic
Scala Generic classes are different then we have generic classes in Java. Generic classes are those classes which takes the type of the variable as the parameter. We are not sure which type of variable would be we just specify it in square brackets []. The type would be verified by the compiler at runtime. Generic classes are mostly utilized for the collection in scala. We mostly use parameter name as A to define the generic class type but it is not mandatory we can use any character to define it.
Syntax:
class class_name[A] {
private varvaribale_name: List[A]
}
In the syntax above we are using A as the type for the list we are defining. This A can contain any data type like Int, Float, String or any other user defined object as well. We can use any other character name as well in the place of A it is the standard that we follow.
class Demo[A] {
private varmyList: List[A] = {20, 30, 40, 50)
}
How does Generic Class Work in Scala?
Collections are very useful when we have same type of data into our list or set. This helps us from typecasting of the elements as well which reduce the line of code. Not with generic we define this type into the [] brackets for example;
using collection :val list = new List[Int] : we are specifying the type at the time of creation only. Now take a look at generic in scala;
using generic : class MyDemo[A] {}
val list = new MyDemo[String]
val list = new MyDemo[Double]
val list = new MyDemo[Float]
val list = new MyDemo[Student]
In the above case, we have created one class with a generic type specify it by using A in the square brackets[]. Now at the time of object creation for the list we are mentioning its type as String or it can be anything we want. If we follow the standard given by scala then the generic parameter should be of single character only. Also, we can have multiple parameter as well see below;
- : class MyClass[Key1, Value1]: In this, we are passing two-parameter here. Also, we can use these parameters with traits in scala which will make them generic too. For syntax how to make them generic see below;
- : trait DemoTrait[Z]: While working with generic in scala we came across the variance types in generic let’s discuss them in detail one by one and consider one case below;
class Flower
class Rose extends Flower
class Jasmin extends Flower
Suppose we have flower class, rose and jasmine are the child class of Flower here. We have different type of variance related to this.
- Question is: If Rose extends Flower so does a list of Rose also extend a list of Flower here from above example?
1. Invariance
IF we chose to answer No for the question then we would require to create the list of Rose and Flower separately and in this case we would use Invariance for this.
class InvariantList[A]
valinvariantAnimalList: InvariantList[Flower] = new InvariantList[Rose]
In this we can define them in scala.
2. Covariance
If we choose to answer yes for the above question then we should go for Covariance here. We can define this Covariance by using the PLUS(+) symbol in the scala. Like this: class CovariantList[+A]
This + simplify that it is a covariance class.
val f: FLower = new Rose
valfList: CovariantList[Flower] = new CovariantList[Rose]
In this example, we are assigning the instance of rose to its parent class because it’s a subclass for flower and creating list for them.
3. Contravariance
If we choose not to answer any of the above then we can go for Contravariance in scala. In this, we use a minus sign (-) to make use of it while working in code. Below is the syntax to use this type in scala:
class ContravariantList[-A]
Examples of Scala Generic Classes
Following are the examples are given below:
1. Single Parameter Generic Classes
In this type we pass only one character to make it Generic in scala. See example below for better understanding;
Code:
object Main extends App{
// Your code here!
// here we are defining the generic type ::::
defaddValues[A](a: A, b: A)(implicit x: Numeric[A]):
//holding value in generic type ::
A = x.plus(a, b)
//printing the output ::
println("Sum of the values are :::: ")
println(addValues(100, 300))
}
Output:
2. Contravariance
To define and use this we use minus operator (-).
Code:
object Main extends App{
// Your code here!
// here we are defining the generic type ::::
valic = new ICICI
valsb = new SBI
valBankType = new BankType
BankType.show(ic)
BankType.show(sb)
}
abstract class Bank [-T]{
defrate : Unit
}
class ICICI extends Bank[Int]{
override def rate: Unit = {
println("icici called ::")
println(" sub type icici !!")
}
}
class SBI extends Bank[Int]{
override def rate: Unit = {
println("SBI called ::")
println("sub type SBI !!")
}
}
class BankType{
defshow(x: Bank[Int]){
x.rate
}
}
Output:
3. Covarience
To define this type we use PLUS (+) operator.
Code:
object Main extends App{
// Your code here!
// here we are defining the generic type ::::
valic = new ICICI
valsb = new SBI
valBankType = new BankType
BankType.show(ic)
BankType.show(sb)
}
abstract class Bank [+T]{
defrate : Unit
}
class ICICI extends Bank[Int]{
override def rate: Unit = {
println("icici called ::")
println(" sub type icici !!")
}
}
class SBI extends Bank[Int]{
override def rate: Unit = {
println("SBI called ::")
println("sub type SBI !!")
}
}
class BankType{
defshow(x: Bank[Int]){
x.rate
}
}
Output:
Conclusion
Generic are important to write efficient code for our application. It makes then code more readable, easily, clear, and also reduces the repetitive logic and line of code in our program. We have discussed its various types also according to the different case we have more better understanding. They are mostly use with collection in scala.
Recommended Articles
We hope that this EDUCBA information on “Scala Generic” was beneficial to you. You can view EDUCBA’s recommended articles for more information.