Scala generic classes take a type as a parameter within square brackets [] and particularly useful for collection classes.

Let us see the following example of Generic classes. We have declared an abstract class Multiplies with x that can accept any data type and define multiply method with y and z variables of x data type after that we have defined two classes Multiint, Multidouble which will accept an integer and double data and then we have created result1 and result2 which will call Multiint and Multidouble methods by passing values and after calculation result will be printed.

Save the program with the name "genericclassexmp.scala" and run it from the terminal by using the command scala genericclassexmp.scala command (refer screenshot).

object genericclassexmp { def main(args: Array[String]) { abstract class Multiply[x] { def multiply(y: x, z: x): x; } class intMultiply extends Multiply[Int] { def multiply(y: Int, z: Int): Int = y * z; } class DoubleMultiply extends Multiply[Double] { def multiply(y: Double, z: Double): Double = y * z; } val result1 = new intMultiply().multiply(10, 20); val result2 = new DoubleMultiply().multiply(10.10, 2.25); println(result1); println(result2); } }

Output

genericclassexmp_example

Click Here To Download Code File.