【发布时间】:2019-03-04 17:36:56
【问题描述】:
我正在学习 Scala 并使用 List 并创建一个字符串列表,如下所示:
val myList = List("Laptop", "Mouse", "Keyboard", "screen")
从文档中,我得到:
scala包中的一个抽象类List,自带两个子类::和Nil
从我得到的类定义中:
@SerialVersionUID(509929039250432923L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B] {
override def tail : List[B] = tl
override def isEmpty: Boolean = false
}
@SerialVersionUID(0 - 8256821097970055419L)
case object Nil extends List[Nothing] {
override def isEmpty = true
override def head: Nothing =
throw new NoSuchElementException("head of empty list")
override def tail: List[Nothing] =
throw new UnsupportedOperationException("tail of empty list")
// Removal of equals method here might lead to an infinite recursion similar to IntMap.equals.
override def equals(that: Any) = that match {
case that1: scala.collection.GenSeq[_] => that1.isEmpty
case _ => false
}
}
但文档没有显示何时创建 NIL 对象以及何时创建 :: 子类对象。
这两者有什么区别,请指教,什么时候用 :: 子类,什么时候用 NIL 子类?
【问题讨论】: