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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9686213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:48:58  来源:igfitidea点击:

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

listscalacollectionsimmutability

提问by fredoverflow

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

什么区别List.emptyList()new List()?我什么时候应该使用哪个?

回答by Travis Brown

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

首先,new List()不起作用,因为List该类是抽象的。另外两个选项被定义为如下List对象

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 emptybecause I find it clearer, and it cuts down on parentheses.

也就是说,它们本质上是等价的,所以这主要是风格问题。我更喜欢使用,empty因为我觉得它更清晰,而且它减少了括号。

回答by Christopher Chiche

From the source code of Listwe have:

List的源代码我们有:

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.

为了完整起见,您还可以使用Nil.

回答by Paolo Falabella

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

但是对于空列表的模式匹配,您只能使用 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.emptydoes not compile

编辑:更正:case List()也可以,但case List.empty不能编译