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
}
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
}
}
首先,我将解释它是什么
List,然后我将解释它是如何工作productIterator的。所以
List- 这是一个抽象类,这意味着您不能创建它的实例。看起来像是List他的继承人之一。该类有List两个后代——案例类::和案例对象Nil。让我们看看它们的实现:
很多人都知道
Nil这是一个空列表,那么我们来考虑case类::。如您所见,它有两个字段 -head和tl. 请注意,它head是单个元素并且tl是一个 collection(List)。那些。当我们写实际上,创建了这样一个案例类:
当你创建时
List(1, 2),它实际上创建了这样的东西:注意第二个参数是 type 的事实
List,这意味着无论你传递(::或Nil)什么后继者 - 它都将显示为List.现在 pro
productIterator,此方法返回类参数的迭代器。在我们的例子中,对象Nil没有参数,类::只有两个参数——head和tl。你可以看到他们的意思。PS
productIterator他们有一个方法——因为他们是一个案例类和一个案例对象。有用的材料: