What is the difference between Nil and List() in Scala?

Scala FAQ: What is the difference between Nil and List() in Scala?

Short answer: There isn’t any difference, as shown in the Scala REPL:

scala> Nil == List()
res0: Boolean = true

It’s more “idiomatic Scala” Scala to use Nil rather than List(). For instance, I wrote code like this last night using Nil in a Scala match/case expression:

post match {
    case '\n' :: rest => splitString(post, acc += pre.mkString)
    case Nil => acc += pre.mkString
    case _ => Nil

But either Nil or List() will work in that situation.

Java’s System.identityHashCode

As a longer answer, this SO post shows a method named System.identityHashCode that I didn’t know about:

scala> System.identityHashCode(Nil)

scala> System.identityHashCode(List())

As I’ll demonstrate shortly, this shows that Nil and List() have the same hash code value. Oracle’s System Javadoc states this about identityHashCode:

"Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode()."

That’s a nice utility.

Manually comparing hash codes

Having seen that fancy approach, I now realize that I can compare Nil and List() in the Scala REPL like this:

scala> Nil.hashCode
res1: Int = 473519988

scala> List().hashCode
res2: Int = 473519988

Again, cool.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.