1

DRY List

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

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可以通过::方法追加新的元素,并返回新的List

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

List可以通过:::连接两个List,并返回新的List

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

horance
255 声望29 粉丝

刘光聪,程序员,敏捷教练,开源软件爱好者,具有多年大型遗留系统的重构经验,对OO,FP,DSL等领域具有浓厚的兴趣。


引用和评论

0 条评论