【问题标题】:Scala: subclass a Java class with multiple constructors?Scala:子类化具有多个构造函数的Java类?
【发布时间】:2013-06-21 19:09:18
【问题描述】:

我正在尝试扩展 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?,但我认为这不是我要找的。谢谢

【问题讨论】:

标签: scala


【解决方案1】:

使用默认值,例如:

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

【讨论】:

  • 如果我想做 new ParentError("Error!"),我还是需要 def this(msg: String) = this(0, msg, null) 对吧?
  • 如果参数顺序不同,您可以使用命名参数:ParentError(msg = "Error!")。这样我将是 0,msg 将是“错误!”并且原因将为空。
猜你喜欢
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2017-12-29
  • 2011-02-01
相关资源
最近更新 更多