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)))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With