By Freewind

2014-06-30 15:46:09 8 Comments

In scala source, I found:

case object Nil extends List[Nothing] {

I can't understand why it is declared as case object rather than object?

I found this question [ Difference between case object and object ] is useful, and I guess this reason is the key:

default implementations of serialization

because we often send list of data to another actor, so Nil must be serializable, right?

With the provided answers(thanks), I try to write some code to verify it:

trait MyList[+T]

object MyNil extends MyList[Nothing]

val list: MyList[String] = MyNil

list match {
  case MyNil => println("### is nil")
  case _ => println("### other list")

You can see MyNil is not case object, but I can still use it in pattern matching. Here is the output:

### is nil

Do I misunderstand something?


@Dave Griffith 2014-06-30 22:24:15

In general for immutable data, the question should never be "why is this a case object (or class)" but rather "Can I make this a case object?". With a few small exceptions (mostly due to inheritance), data elements in Scala should be immutable, and should be implemented via case classes/objects. Given that, implementing Nil and :: as a case object and case class (respectively) is just standard practice, for which there is no downside.

@soldier.moth 2014-06-30 19:45:37

As mentioned in the comments of that linked question, one thing you get is a prettier .toString result

scala> MyNil.toString
res0: String = [email protected]

scala> case object MyNil2 extends MyList[Nothing]
defined module MyNil2

scala> MyNil2.toString
res2: String = MyNil2

scala> Nil.toString
res1: String = List()

Related Questions

Sponsored Content

20 Answered Questions

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

10 Answered Questions

[SOLVED] Why is it string.join(list) instead of list.join(string)?

  • 2009-01-29 22:45:13
  • Evan Fosmark
  • 1251765 View
  • 1698 Score
  • 10 Answer
  • Tags:   python string list

10 Answered Questions

[SOLVED] OR is not supported with CASE Statement in SQL Server

5 Answered Questions

[SOLVED] null object in Python?

  • 2010-07-20 11:53:41
  • Lizard
  • 1514267 View
  • 1131 Score
  • 5 Answer
  • Tags:   python null

19 Answered Questions

[SOLVED] How to Sort a List<T> by a property in the object

1 Answered Questions

[SOLVED] Scala, Akka: pattern matching for object in trait issue

  • 2017-06-15 22:49:30
  • Mikekekeke
  • 130 View
  • 0 Score
  • 1 Answer
  • Tags:   scala akka

2 Answered Questions

[SOLVED] Why are case objects serializable and case classes not?

Sponsored Content