Scala:使用多个构造函数子类化Java类?

时间:2013-06-21 19:09:18

标签: scala

我正在尝试扩展Java Exception类,但结果非常丑陋且笨拙。 所以,我不确定自己是否走在正确的轨道上。有没有更好的方法呢?

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
}

注意:我看到In Scala, how can I subclass a Java class with multiple constructors?,但我认为这不是我想要的。感谢

1 个答案:

答案 0 :(得分:4)

使用默认值,例如:

class ParentError(i: Double = 0, msg: String = null, cause: Throwable = null)
      extends Exception(msg: String, cause: Throwable) {
      ⋮
}