简体   繁体   中英

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM