Generic in Scala
Generic classes are classes which take a type as a parameter. They are useful for collection classes. Generic classes can be used in everyday data implementation, such as stack, queue, linked list, and so on. We will see some examples.
Defining a generic class
Generic classes take a type as a parameter within square brackets []
. One is to use the letter A
as a type parameter identifier, though any parameter name may be used. Let's see a minimal example on Scala REPL, as follows:
scala> class Stack[A] { | private var elements: List[A] = Nil | def push(x: A) { elements = x :: elements } | def peek: A = elements.head | def pop(): A = { | val currentTop = peek | elements = elements.tail | currentTop | } | } defined class Stack scala>
The preceding implementation of a Stack
class takes any type A as a parameter. This means the underlying list, var elements: List[A] =...