Scala Constructor 模式与 Extractor 模式匹配

标签 scala pattern-matching

构造器模式和抽取器模式匹配有什么区别? 在 Programming in Scala 中,作者区分了第 15 章中讨论的构造函数模式和第 26 章中讨论的提取器模式。

构造函数模式的例子:

abstract class Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr

expr match {
    case BinOp("+", e, Number(0)) => println("a deep match")
    case _ => 
}

提取器示例:

l match {
     case List(a,b,c) => a
     case _ =>
}

最佳答案

区别在规范中表示:

An extractor pattern x(p1, …, pn) where n ≥ 0 is of the same syntactic form as a constructor pattern. However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matches the pattern.

简单地说,构造函数模式讨论案例类的分解,其中提取器模式讨论任何具有 unapplyunapplySeq 的对象。

List[A] 有一个 unapplySeq 由抽象 SeqFactory 提供:

/** This method is called in a pattern match { case Seq(...) => }.
 *
 *  @param x the selector value
 *  @return  sequence wrapped in an option, if this is a Seq, otherwise none
 */
def unapplySeq[A](x: CC[A]): Some[CC[A]] = Some(x)

关于Scala Constructor 模式与 Extractor 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622811/

相关文章:

java - Java 中的正则表达式分组

scala - 使用 Play2 scala 的 Heroku 内存泄漏

scala - 我们可以使用单例 .type 作为类型参数吗?

c++ - C++ 中的高效字符串/模式匹配(后缀数组、特里树、后缀树?)

空集上的 Haskell 模式匹配

regex - 在 postgres 中一起使用 REPLACE 和 LIKE

java - 在图像中寻找模式

scala - 编译器选项警告与 linter

scala - 在 Slick 中一次和多次调用 `run.db` 有什么不同吗

scala - 运行 Maven scala 项目