What are Generic Classes in Scala?
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.
Naming convensions
Generic classes in Scala have particular naming conventions when implementing a class.
- Letter A is written inside
[]as a type parameter - Symbol used to denote a key is A and for a value, it is B
- Symbol used to denote a numeric value is N
Syntax
class MyList[A] {
// Some methods or objects.
}
Code
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)}}
Explanation
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
Copyright ©2025 Educative, Inc. All rights reserved