Why is `Nil` defined as a` case object`

In the scala source, I found:

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

I can’t understand why it is declared as a case object and not an object ?

I found this question [ The difference between an object of an object and an object ] useful, and I believe that this reason is the key:

default serialization implementation

because we often send a list of data to another player, so Nil has to be serializable, right?


With the answers provided (thanks), I'm trying to write 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 that MyNil not a case object , but I can still use it according to the pattern. Here is the result:

 ### is nil 

Am I misunderstanding something?

+7
list null scala case
source share
2 answers

In general, for immutable data, the question should never be β€œwhy is it an object-object (or class)”, but rather β€œCan I make a case object?”. With a few exceptions (mainly due to inheritance), data elements in Scala must be immutable and must be implemented through case classes / objects. Given that implementing Nil and :: as a case object and a case class (respectively) is standard practice for which there are no drawbacks.

+5
source share

As mentioned in the comments on this related question, the one thing you get is a more beautiful .toString result

 scala> MyNil.toString res0: String = MyNil$@51aa572b scala> case object MyNil2 extends MyList[Nothing] defined module MyNil2 scala> MyNil2.toString res2: String = MyNil2 scala> Nil.toString res1: String = List() 
+2
source share

All Articles