【发布时间】:2018-06-02 19:55:41
【问题描述】:
使用 Scala 的 api documentation 很明显,列表是如何使用 :: 语法构造的,它指的是列表上的方法。
但是{ case 1 :: 2 :: _ => ??? } 中用于模式匹配的中缀表示法提取器需要一个带有 unapply 方法的对象。
所以我的问题是:这个无证提取器 :: 在 Scala 中来自哪里?
【问题讨论】:
使用 Scala 的 api documentation 很明显,列表是如何使用 :: 语法构造的,它指的是列表上的方法。
但是{ case 1 :: 2 :: _ => ??? } 中用于模式匹配的中缀表示法提取器需要一个带有 unapply 方法的对象。
所以我的问题是:这个无证提取器 :: 在 Scala 中来自哪里?
【问题讨论】:
:: 的实现如下所示
/** 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
}
欲了解更多信息,请访问Scala's '::' operator, how does it work?
【讨论】:
case class生成提取器。
对于列表上的::,提取器作为case class :: 的一部分生成。
在模式匹配中使用:: 称为构造函数模式。
【讨论】: