Scala源码探索之"::"

本文详细解析了Scala中List类的::方法实现原理,通过具体示例解释了如何使用该方法在列表前添加元素,并深入探讨了其内部构造机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看这个表达式

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]作为Listtail

整个过程比较顺畅,其他比较容易理解,但是

  def ::[B >: A] (x: B): List[B] =
    new scala.collection.immutable.::(x, this)

这里的[B >: A]是什么意思?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值