跟进scala构造函数重载

时间:2012-12-11 08:15:51

标签: scala constructor override case-class

这是Scala constructor overload?的后续问题我想要一个案例类构造函数,它在输入的受限形式上运行,因此覆盖,而不是重载构造函数:

abstract class Expr

case class RegExpr(regex : Regex) extends Expr {
  override def this(regex : Regex) = {
    if (regex.toString contains "*") 
     throw new Exception("Restricted class of regular expressions: cannot contain Kleene star.")
    else if (regex.toString contains "|")
      throw new Exception("Restricted class of regular expressions: cannot contain disjunction.")
    else this(regex)
  }
}

这不编译;我已经尝试了几次不同的迭代,但他们都回到编译器告诉我它期望'这',但是'if'被找到了。我如何得到我想要的行为?

1 个答案:

答案 0 :(得分:5)

不需要两个构造函数。只需在班级中添加支票,它们将在施工时运行。

case class RegExpr(regex: Regex) extends Expr {
   if (regex.toString contains "*") throw ...
   if (regex.toString contains "|") throw ...


}