【问题标题】:Difference between :: and Nil types in ScalaScala 中 :: 和 Nil 类型的区别
【发布时间】: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 子类?

【问题讨论】:

    标签: scala list subclass


    【解决方案1】:

    当您使用List(..) 语法时,编译器将使用List 的伴随对象中定义的List.apply:

    override def apply[A](xs: A*): List[A] = xs.toList
    

    您实际上看不到列表的创建,因为它是根据 Scala 集合库的定义方式一般创建的。

    ::和Nil的区别在于前者代表一个有头有尾的链表,后者代表一个不包含任何元素的空链表。

    我们也可以直接使用::和Nil定义一个列表:

    val list = "Laptop" :: "Mouse" :: "Keyboard" :: Nil
    

    翻译成:

    val list = Nil.::("Keyboard").::("Mouse").::("Laptop")
    

    其中:: 不是指:: 类型,而是指List[A] 上的方法:

    def ::[B >: A] (x: B): List[B] = new scala.collection.immutable.::(x, this)
    

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多