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

30,558

Solution 1

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.

Solution 2

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.

Solution 3

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

Share:
30,558
fredoverflow
Author by

fredoverflow

Updated on March 14, 2020

Comments

  • fredoverflow
    fredoverflow about 4 years

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