July 2017
Intermediate to advanced
796 pages
18h 55m
English
Generic classes take a type as a parameter within square brackets []. One convention 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 Stackscala>
The preceding implementation of a Stack class takes any type A as a parameter. This means the underlying list, var elements: List[A] = Nil can only store elements of type A. The procedure def push only accepts objects of type A (note: ...
Read now
Unlock full access