Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class parameter (generics) for singleton object

Tags:

scala

In his course on Coursera, professor Martin Odesrky uses a linked list as an example in a lecture about polymorphism and parameterized classes:

package week4

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 = false
}
class Nil[T] extends List[T] {
  def isEmpty = true
  def head = throw new NoSuchElementException("Nil.head")
  def tail = throw new NoSuchElementException("Nil.tail")
}
object Main extends App {
  def main(args: Array[String]) {
    val lst = new Cons("A", new Cons("B", new Cons("C", new Nil())))
  }
}

What bothers me is the instantiation of class Nil in the last lines, new Nil().

How would one define Nil as an object instead of as a Scala class, and have it conform to the parameterized type List[T] ?

I'd like to refer to the object Nil as in the following line of code (no instantiation), and make it have the correct type

new Cons("A", new Cons("B", new Cons("C", Nil)))
like image 236
Leonel Avatar asked Feb 16 '23 19:02

Leonel


1 Answers

In the actual Scala library (List.scala) here's how it is done,

case object Nil extends List[Nothing] { ...

Probably in the class he wanted to avoid introducing Nothing, which is the type at the bottom of Scala's type lattice.

like image 199
Kipton Barros Avatar answered Feb 27 '23 23:02

Kipton Barros