스칼라, 모든 사이에 어떤 차이가 Nil
하고List()
?
그렇지 않다면 어느 것이 관용 스칼라 스타일입니까? 비어있는 새 목록을 만들고 비어있는 목록에서 패턴을 일치시킵니다.
답변
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
및 모두의 런타임 값이 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
이는 폴드 누산기와 같이 유형을 유추하는 데 사용될 때 특히 중요합니다.
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)
^
답변
사용자 알 수 없음의 답변에서 알 수 있듯이 동일한 객체입니다.
관용적으로 Nil이 좋으며 짧기 때문에 선호됩니다. 그래도 예외가 있습니다 : 어떤 이유로 든 명시 적 유형이 필요한 경우
List[Foo]()
보다 좋다
Nil : List[Foo]