1

I am trying to extend Java Exception class but the result is pretty ugly and clumsy. So, I am not sure that I am on the right track. Any better way to do this?

class ParentError(_d: Double, msg: String, cause: Throwable)
      extends Exception(msg: String, cause: Throwable) {
  def this() = this(0, null, null)
  def this(d: Double) = this(d, null, null)
  def this(msg: String) = this(0, msg, null)
  def this(msg: String, cause: Throwable) = this(0, msg, cause)
  def this(cause: Throwable) = this(0, null, cause)
  def i = _d
}

case class ChildError(_b: Boolean, _i: Double, msg: String, cause: Throwable)
      extends ParentError(_i: Double, msg: String, cause: Throwable) {
  def this(b: Boolean) = this(b, 0, null, null)
  def this(msg: String) = this(false, 0, msg, null)
  def this(msg: String, cause: Throwable) = this(false, 0, msg, cause)
  def this(cause: Throwable) = this(false, 0, null, cause)
  def b = _b
}

Note:I saw In Scala, how can I subclass a Java class with multiple constructors? but I don't think it's what I'm looking for. Thanks

Community
  • 1
  • 1
pt2121
  • 11,720
  • 8
  • 52
  • 69
  • 2
    possible duplicate of [define your own exceptions with overloaded constructors in scala](http://stackoverflow.com/questions/10925268/define-your-own-exceptions-with-overloaded-constructors-in-scala) – senia Jun 21 '13 at 19:11

1 Answers1

7

Use default values, for example:

class ParentError(i: Double = 0, msg: String = null, cause: Throwable = null)
      extends Exception(msg: String, cause: Throwable) {
      ⋮
}
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • If I want to do new ParentError("Error!"), I still need def this(msg: String) = this(0, msg, null) anyway, right? – pt2121 Jun 21 '13 at 19:30
  • If args order differs, you could use named args: `ParentError(msg = "Error!")`. This way i will be 0, msg will be "Error!" and cause will be null. – om-nom-nom Jun 21 '13 at 19:32
  • I search a lot for this answer. Glad I finally found it here. – Eric Green Jun 18 '22 at 17:25