无法实例化构造函数

问题描述 投票:0回答:1

我有以下简单的代码:

package week_4

object Pattern_matching {
  trait Expr
  case class Number(n: Int) extends Expr {}
  case class Sum(e1: Expr, e2: Expr) extends Expr {}

  def eval: Int = this match {
    case Number(n) => n
    case Sum(e1, e2) => e1.eval + e2.eval
  }
}

我得到的错误在第9行和第10行。在数据类型方面我怎么理解?

(错误消息是:构造函数无法实例化为预期类型;找到:week_4.Pattern_matching.Sum required:week_4.Pattern_matching.type)

scala pattern-matching
1个回答
1
投票

看看this。它只能是类型Pattern_matching所以它不能是任何一个case类。而Expr特质没有eval成员。

我猜你想要这样的东西。

object Pattern_matching {
  trait Expr {
    def eval: Int = this match {
      case Number(n) => n
      case Sum(e1, e2) => e1.eval + e2.eval
    }
  }

  case class Number(n: Int) extends Expr
  case class Sum(e1: Expr, e2: Expr) extends Expr
}
© www.soinside.com 2019 - 2024. All rights reserved.