【问题标题】:Scala: Undocumented Extractor `::`Scala:无证提取器`::`
【发布时间】:2018-06-02 19:55:41
【问题描述】:

使用 Scala 的 api documentation 很明显,列表是如何使用 :: 语法构造的,它指的是列表上的方法。

但是{ case 1 :: 2 :: _ => ??? } 中用于模式匹配的中缀表示法提取器需要一个带有 unapply 方法的对象。 所以我的问题是:这个无证提取器 :: 在 Scala 中来自哪里?

【问题讨论】:

    标签: scala pattern-matching


    【解决方案1】:

    :: 的实现如下所示

    /** 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?

    【讨论】:

    • 谢谢。这是正确的,我的假设不是:此代码也是documented。我一开始以为,每个案例类都会生成一个对应的对象,但这可能是一个实现细节。
    • 是的,默认为case class生成提取器。
    【解决方案2】:

    对于列表上的::,提取器作为case class :: 的一部分生成。 在模式匹配中使用:: 称为构造函数模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多