Scala:Nil 与 List()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5981850/
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
Scala: Nil vs List()
提问by Bart
In Scala, is there any difference at all between Niland List()?
在 Scala 中,Nil和之间有什么区别List()吗?
If not, which one is more idiomatic Scala style? Both for creating new empty lists and pattern matching on empty lists.
如果不是,哪一种更符合 Scala 风格?两者都用于创建新的空列表和空列表上的模式匹配。
回答by user unknown
scala> println (Nil == List())
true
scala> println (Nil eq List())
true
scala> println (Nil equals List())
true
scala> System.identityHashCode(Nil)
374527572
scala> System.identityHashCode(List())
374527572
Nil is more idiomatic and can be preferred in most cases. Questions?
Nil 更惯用,在大多数情况下可以首选。问题?
回答by Daniel C. Sobral
User unknownhas shown that the run time value of both Niland List()are the same. However, their static type is not:
未知的用户表明,两者的运行时间值Nil和List()是相同的。但是,它们的静态类型不是:
scala> val x = List()
x: List[Nothing] = List()
scala> val y = Nil
y: scala.collection.immutable.Nil.type = List()
scala> def cmpTypes[A, B](a: A, b: B)(implicit ev: A =:= B = null) = if (ev eq null) false else true
cmpTypes: [A, B](a: A, b: B)(implicit ev: =:=[A,B])Boolean
scala> cmpTypes(x, y)
res0: Boolean = false
scala> cmpTypes(x, x)
res1: Boolean = true
scala> cmpTypes(y, y)
res2: Boolean = true
This is of particular importance when it is used to infer a type, such as in a fold's accumulator:
这在用于推断类型时特别重要,例如在折叠的累加器中:
scala> List(1, 2, 3).foldLeft(List[Int]())((x, y) => y :: x)
res6: List[Int] = List(3, 2, 1)
scala> List(1, 2, 3).foldLeft(Nil)((x, y) => y :: x)
<console>:10: error: type mismatch;
found : List[Int]
required: scala.collection.immutable.Nil.type
List(1, 2, 3).foldLeft(Nil)((x, y) => y :: x)
^
回答by James Iry
As user unknown's answer shows, they are the same object.
正如用户未知的答案所示,它们是同一个对象。
Idiomatically Nil should be preferred because it is nice and short. There's an exception though: if an explicit type is needed for whatever reason I think
惯用的 Nil 应该是首选,因为它很好而且很短。但是有一个例外:如果出于我认为的任何原因需要显式类型
List[Foo]()
is nicer than
比
Nil : List[Foo]

