fredoverflow
fredoverflow

Reputation: 263078

List.empty vs. List() vs. new List()

What the difference between List.empty, List() and new List()? When should I use which?

Upvotes: 31

Views: 33844

Answers (3)

Paolo Falabella
Paolo Falabella

Reputation: 25834

For the creations of an empty list, as others have said, you can use the one that looks best to you.

However for pattern matching against an empty List, you can only use Nil

scala> List()
res1: List[Nothing] = List()

scala> res1 match {
     | case Nil => "empty"
     | case head::_ => "head is " + head
     | }
res2: java.lang.String = empty

EDIT : Correction: case List() works too, but case List.empty does not compile

Upvotes: 4

Christopher Chiche
Christopher Chiche

Reputation: 15325

From the source code of List we have:

object List extends SeqFactory[List] {
  ...
  override def empty[A]: List[A] = Nil
  override def apply[A](xs: A*): List[A] = xs.toList
  ... 
}

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

So we can see that it is exactly the same

For completeness, you can also use Nil.

Upvotes: 12

Travis Brown
Travis Brown

Reputation: 139028

First of all, new List() won't work, since the List class is abstract. The other two options are defined as follows in the List object:

override def empty[A]: List[A] = Nil
override def apply[A](xs: A*): List[A] = xs.toList

I.e., they're essentially equivalent, so it's mostly a matter of style. I prefer to use empty because I find it clearer, and it cuts down on parentheses.

Upvotes: 36

Related Questions