Generic Classes are classes that take a type
– just like a parameter – inside the square brackets[]
.
This type of class is useful for collection classes.
Generic classes in Scala have particular naming conventions when implementing a class.
[]
as a type parameterclass MyList[A] {
// Some methods or objects.
}
Let’s look at the implementation of Generic Classes through the following example:
object GenericClass {def main(args: Array[String]) : Unit = {abstract class Addition[A] {def addition(b: A, c: A): A}class intAddition extends Addition[Int] {def addition(b: Int, c: Int): Int = b + c}class doubleAddition extends Addition[Double] {def addition(b : Double, c : Double) : Double = b + c}val add1 = new intAddition().addition(69, 5)val add2 = new doubleAddition().addition(30.0, 8.0)println(add1)println(add2)}}
The above code snippet implements a Generic Class, demonstrating how we can use the same function (i.e., addition()
) in multiple classes to add distinct data types and display their respective results.
Free Resources