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.
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.
The sum is : 100
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.