Scala Language Generic collection


Defining the list of Ints

trait IntList { ... }

class Cons(val head: Int, val tail: IntList) extends IntList { ... }

class Nil extends IntList { ... }

but what if we need to define the list of Boolean, Double etc?

Defining generic list

trait List[T] {
  def isEmpty: Boolean
  def head: T
  def tail: List[T]

class Cons[T](val head: [T], val tail: List[T]) extends List[T] {
  def isEmpty: Boolean = false

class Nil[T] extends List[T] {
  def isEmpty: Boolean = true

  def head: Nothing = throw NoSuchElementException("Nil.head")

  def tail: Nothing = throw NoSuchElementException("Nil.tail")