Programing

스칼라 : 닐 vs리스트 ()

lottogame 2020. 7. 15. 07:34
반응형

스칼라 : 닐 vs리스트 ()


스칼라 년 사이에 전혀 차이가 NilList()?

그렇지 않다면 어느 것이 관용 스칼라 스타일입니까? 비어있는 새 목록을 만들고 비어있는 목록에서 패턴을 일치시킵니다.


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]

참고URL : https://stackoverflow.com/questions/5981850/scala-nil-vs-list

반응형