我正在玩模式匹配,但我有一些难以理解这段代码有什么问题:
class Expr {
case class Number(v : Int) extends Expr
case class Sum(a : Expr, b : Expr) extends Expr
def show(e: Expr): String = {
e match {
case Number(a) => a.toString()
case Sum(a, b) => "(" + show(a) + "+" + show(b) + ")"
}
}
override def toString() = show(this)
}
class Number(v : Int) extends Expr
class Sum(a : Expr, b : Expr) extends Expr
object Number {
def apply(v : Int) = new Number(v)
}
object Sum extends Expr {
def apply(a : Expr, b : Expr) = new Sum(a, b)
}
object ExpressionProblem {
def main(args: Array[String]) {
val p = Sum( Number(3), Number(4))
println( p )
}
}
当我尝试执行println
时,它会抛出MatchError。
Exception in thread "main" scala.MatchError: an instance of class week4.Expr$Sum
at week4.Expr.show(ExpressionProblem.scala:8)
at week4.Expr.toString(ExpressionProblem.scala:14)
at java.lang.String.valueOf(String.java:2994)
at java.io.PrintStream.println(PrintStream.java:821)
at scala.Console$.println(Console.scala:148)
at scala.Predef$.println(Predef.scala:315)
at week4.ExpressionProblem$.main(ExpressionProblem.scala:31)
at week4.ExpressionProblem.main(ExpressionProblem.scala)
答案 0 :(得分:4)
您正在发送Sum
课程的实例,但尝试匹配Sum
案例类的实例。删除类并使代码类可见:
trait Expr {
def show(e: Expr): String = e match {
case Number(a) => a.toString()
case Sum(a, b) => "(" + show(a) + "+" + show(b) + ")"
}
override def toString() = show(this)
}
case class Number(v : Int) extends Expr
case class Sum(a : Expr, b : Expr) extends Expr
object ExpressionNoProblem {
def main(args: Array[String]) {
val p = Sum(Number(3), Number(4))
println(p)
}
}