看这个表达式
val prg = "6 * 3 " :: "24-/*aaa*/4" :: "a+5" :: "21/3" :: Nil
打印出来,可以得到List(6 * 3 , 24-/*aaa*/4, a+5, 21/3)
找到::的源码,这是一个属于List类的方法
/** Adds an element at the beginning of this list.
* @param x the element to prepend.
* @return a list which contains `x` as first element and
* which continues with this list.
*
* @usecase def ::(x: A): List[A]
* @inheritdoc
*
* Example:
* {{{1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)}}}
*/
def ::[B >: A] (x: B): List[B] =
new scala.collection.immutable.::(x, this)
发现这里new了一个immutable.::类,继续看::模板类
/** A non empty list characterized by a head and a tail.
* @param head the first element of the list
* @param tl the list containing the remaining elements of this list after the first one.
* @tparam B the type of the list elements.
* @author Martin Odersky
* @version 1.0, 15/07/2003
* @since 2.8
*/
@SerialVersionUID(509929039250432923L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
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
}
上面代码可以看到,就是把传入的参数tl: List[B]作为List的tail。
整个过程比较顺畅,其他比较容易理解,但是
def ::[B >: A] (x: B): List[B] =
new scala.collection.immutable.::(x, this)
这里的[B >: A]是什么意思?
Scala List::方法解析
本文详细解析了Scala中List类的::方法实现原理,通过具体示例解释了如何使用该方法在列表前添加元素,并深入探讨了其内部构造机制。
600

被折叠的 条评论
为什么被折叠?



