Generic Classes in Scala
Last Updated :
25 Apr, 2019
In Scala, forming a Generic Class is extremely analogous to the forming of generic classes in Java. The classes that takes a type just like a parameter are known to be Generic Classes in Scala. This classes takes a type like a parameter inside the square brackets i.e, [ ]. This classes are utilized explicitly for the progress of the collection classes in Scala. The sub-typing of generic types is invariant i.e, if we have two list types, A and B then List[A] is sub-type of List[B] if and only if type B is equivalent to type A.
Some points to remember:
- The symbol used for a type parameter of a simple type is A, like List[A].
- The symbols used for a type parameter of second, third, fourth, and so on, types in generic classes are respectively B, C, D, and so on.
- The symbol used for a key is A and for a value is B in Scala Map.
- The symbol used for a numeric value is N.
Note: Though this symbol conventions are provided, still any symbol can be used for the type parameters.
let’s discuss some examples below.
Example:
object GfG
{
def main(args : Array[String])
{
abstract class Divide[z]
{
def divide(u : z, v : z) : z
}
class intDivide extends Divide[Int]
{
def divide(u : Int, v : Int) : Int = u / v
}
class doubleDivide extends Divide[Double]
{
def divide(u : Double, v : Double) : Double = u / v
}
val q = new intDivide().divide( 25 , 5 )
val r = new doubleDivide().divide( 21.0 , 5.0 )
println(q)
println(r)
}
}
|
Here, the abstract class Divide has a type parameter z, and it is present in the square brackets so the class is generic type, this type parameter z can take up each and every data types. we have defined a method divide inside the Generic class which has two variables i.e, u and v and the data type of these variables is z. The class intDivide, as stated above take up integer types and the class doubleDivide, as stated above take up double types. Thus, the type parameter z was replaced by Int and Double data types. By this way sub-typing is possible in Generic classes.
Example :
import Numeric. _
object GfG
{
def main(args : Array[String])
{
def addition[N](a : N, b : N)( implicit num : Numeric[N]) :
N = num.plus(a, b)
println( "The sum is : " +addition( 88 , 12 ))
}
}
|
Here, we saw generic type parameter for numeric values and so, we have used symbol N here though any symbol can be used as a type parameter for a generic types.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...