在Scala中的模式匹配器中访问匹配对象
我目前正在Coursera上学习Scala函数编程原理课程,我刚刚学习了模式匹配。我试图做一些似乎不可能的事情,我想知道什么是正确的习惯用法 以下是课程中的一些代码:在Scala中的模式匹配器中访问匹配对象,scala,functional-programming,pattern-matching,Scala,Functional Programming,Pattern Matching,我目前正在Coursera上学习Scala函数编程原理课程,我刚刚学习了模式匹配。我试图做一些似乎不可能的事情,我想知道什么是正确的习惯用法 以下是课程中的一些代码: trait Expr case class Number(n: Int) extends Expr { def next = n + 1 // I've added this method } case class Sum(e1: Expr, e2: Expr) extends Expr def show(e: Expr):
trait Expr
case class Number(n: Int) extends Expr {
def next = n + 1 // I've added this method
}
case class Sum(e1: Expr, e2: Expr) extends Expr
def show(e: Expr): String = e match {
case Number(n) => n.toString
case Sum(l, r) => show(l) + " + " + show(r)
}
当您使用模式匹配器时,您可以访问匹配对象的参数,如n表示Numbern,但无法访问匹配对象的Numbern。例如,我希望这样:
case Number(n) => 'referenceToMatchedObject'.next
我知道我可以做case Numbern=>Numbern.next,但这并不优雅
也许我仍然在考虑OO风格,但我觉得能够添加可以应用于匹配对象的特定函数很好
另一个例子:假设我有一个动物特征/抽象类和一个猫类。Cat类是唯一具有函数爬树的类。在模式匹配器中,我想让猫爬树
做这样的事情,Scala函数式的正确方法是什么 这就是你想要的:
def show2(e: Expr): String = e match {
case n @ Number(1) => n.next.toString
case n : Number => n.next.toString
case Sum(l, r) => show(l) + " + " + show(r)
}
好的,很酷,所以我可以在类型上匹配。但我无法匹配数字1,但仍然可以访问acutal对象?这可能没有意义,首先你可以这样做:case n@Number1=>n.next.toStringYep就是这样!我刚刚读完关于模式匹配的官方文档,没有提到这种绑定操作符