Scala Essentials: 剖析 List
文章目录
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))
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论