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

别来无恙 提交于 2019-12-03 10:42:47

问题


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


回答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.




回答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.




回答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



来源:https://stackoverflow.com/questions/9686213/list-empty-vs-list-vs-new-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!