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))
相關文章
相關標籤/搜索