Bostonian
Bostonian

Reputation: 687

object extends trait v.s class extends trait

What is the benefit we declare object Nil to extends TweetList? why not still use class Nil?

trait TweetList {
  def head: Tweet
  def tail: TweetList
  def isEmpty: Boolean
  def foreach(f: Tweet => Unit): Unit =
    if (!isEmpty) {
      f(head)
      tail.foreach(f)
    }
}

object Nil extends TweetList {
  def head = throw new java.util.NoSuchElementException("head of EmptyList")
  def tail = throw new java.util.NoSuchElementException("tail of EmptyList")
  def isEmpty = true
}

class Cons(val head: Tweet, val tail: TweetList) extends TweetList {
  def isEmpty = false
}

Upvotes: 0

Views: 101

Answers (1)

osehyum
osehyum

Reputation: 145

Here's a link for how to use singleton class.

Above comments also mentioned about it, but I explain it again.

In scala, object declaration is used for singleton objects. In this case, Nil's role is of representing 'emptiness' and is used as last parameters of successive cons

cons(a, Nil) => List(a)
cons(a, cons(b, Nil)) => List(a, b)

So why Nil is object and extends List? cause,

  • Nil is used as single representation of emptiness of List.

We don't need multiple instances of Nil. It also makes sense that 2nd parameter of cons is List type.

Upvotes: 1

Related Questions