0

我需要有一个HugeDecimal继承自java.math.BigDecimal. 由于内部原因,它不能成为一种特征。以下简单实现:

class HugeDecimal extends java.math.BigDecimal {
}

引发此错误:

Error:(1187, 37) overloaded method constructor BigDecimal with alternatives:
  (x$1: Long,x$2: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: Long)java.math.BigDecimal <and>
  (x$1: Int,x$2: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: Int)java.math.BigDecimal <and>
  (x$1: java.math.BigInteger,x$2: Int,x$3: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: java.math.BigInteger,x$2: Int)java.math.BigDecimal <and>
  (x$1: java.math.BigInteger,x$2: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: java.math.BigInteger)java.math.BigDecimal <and>
  (x$1: Double,x$2: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: Double)java.math.BigDecimal <and>
  (x$1: String,x$2: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: String)java.math.BigDecimal <and>
  (x$1: Array[Char],x$2: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: Array[Char])java.math.BigDecimal <and>
  (x$1: Array[Char],x$2: Int,x$3: Int,x$4: java.math.MathContext)java.math.BigDecimal <and>
  (x$1: Array[Char],x$2: Int,x$3: Int)java.math.BigDecimal
 cannot be applied to ()

我知道我可以做到:

class HugeDecimal(d: Double) extends java.math.BigDecimal(d) {
  def this(str: String) = this(str.toDouble)
  def this(i: Int) = this(i.toDouble)
}

但我需要能够从超类继承所有构造函数,而不支持任何单个超类构造函数。即,我需要将String构造函数调用超类的String构造函数。

答案Scala 从 Java 类继承:选择要调用的超级构造函数在 Scala 中,如何子类化具有多个构造函数的 Java 类?建议使用辅助构造函数委托给的特征或主构造函数,但这些都不适用于我的场景,因为我需要从可以调用以下内容的 Java 代码中访问:

new HugeDecimal("12.34")
new HugeDecimal(1234)

我有什么解决方案,还是需要用 Java 实现这个类?

4

1 回答 1

2

您不能继承构造函数。用 java 还是 scala 实现它都没有关系,如果你想有几个构造函数,你必须实现它们中的每一个。

于 2018-01-07T17:09:21.527 回答