Scala Essentials: 剖析 List

DRY List

Nil对象定义在scala.collection.immutable.List中。ide

package scala.collection.immutable

sealed abstract class List[+A] {
  def isEmpty: Boolean
  def head: A
  def tail: List[A]
  
  def ::[B >: A] (x: B): List[B] =
    new scala.collection.immutable.::(x, this)

  def :::[B >: A](prefix: List[B]): List[B] =
    if (isEmpty) prefix
    else if (prefix.isEmpty) this
    else (new ListBuffer[B] ++= prefix).prependToList(this)
}

final case class ::[B](private var hd: B, private var tl: List[B]) extends List[B] {
  override def head : B = hd
  override def tail : List[B] = tl
  override def isEmpty: Boolean = false
}

case object Nil extends List[Nothing] {
  override def isEmpty = true
  override def head: Nothing = throw new NoSuchElementException("empty list")
  override def tail: List[Nothing] = throw new UnsupportedOperationException("empty list")
}

Nil能够经过::方法追加新的元素,并返回新的Listthis

1 :: 2 :: Nil  // Nil.::(2).::(1), List(1, 2)

List能够经过:::链接两个List,并返回新的Listscala

List(1, 2) ::: Nil  // Nil.:::(List(1, 2))
相关文章
相关标签/搜索