0

This is a followup question to Scala constructor overload? I'd like a case class constructor that operates on a restricted form of the input and so overrides, rather than overloads the constructor:

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)
  }
}

This doesn't compile; I've tried a couple different iterations of this, but they all come back to the compiler telling me it expects 'this', but 'if' is found instead. How do I get the behavior I want?

Community
  • 1
  • 1
etosch
  • 180
  • 7

1 Answers1

5

There is no need for two constructors. Just add the check inside the class, they will be run at construction time.

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


}
Didier Dupont
  • 29,398
  • 7
  • 71
  • 90