构造器模式和抽取器模式匹配有什么区别? 在 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)
wheren ≥ 0
is of the same syntactic form as a constructor pattern. However, instead of a case class, the stable identifierx
denotes an object which has a member method named unapply or unapplySeq that matches the pattern.
简单地说,构造函数模式讨论案例类的分解,其中提取器模式讨论任何具有 unapply
或 unapplySeq
的对象。
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/