java - Java 构造函数的 Scala 继承

标签 java scala inheritance constructor multiple-constructors

我需要一个从 java.math.BigDecimal 继承的 Scala 类 HugeDecimal。由于内部原因,它不可能成为一种特征。简单实现如下:

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

但是我需要能够从父类(super class)继承所有构造函数,而不偏向任何单个父类(super class)构造函数。即,我需要 String 构造函数调用父类(super class)的 String 构造函数。

答案Scala inheritance from Java class: select which super constructor to callIn Scala, how can I subclass a Java class with multiple constructors?建议使用特征或由辅助构造函数委托(delegate)给的主构造函数,但是这些都不适合我的场景,因为我需要从可以调用以下内容的 Java 代码进行访问:

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

我有什么解决方案吗,或者我需要用Java实现这个类吗?

最佳答案

您不能继承构造函数。不管你是用java还是scala实现它,如果你想要有多个构造函数,你就必须实现它们中的每一个。

关于java - Java 构造函数的 Scala 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48139508/

相关文章:

scala - SBT:列出项目依赖库

c++ - 父级上 protected 构造函数和继承的默认构造函数不 protected

php - 在 PHP 中更改父属性的值

c++ - 如何在 C++ 中从模板基类的构造函数调用模板父类(super class)的构造函数?

java - Bigdecimal 不给出小数点后的结果

java - 如何暂时禁止项目中的包在 Java EE IDE 中编译

java - 在 java 中使用 HttpAsyncClients 实现“即发即忘”

scala - 使用 shadowJar 和 Scala 依赖项时如何修复丢失的 conf 文件?

java - 我如何在 Wicket 1.5 中模仿 HybridUrlCodingStrategy?

Scala 按未知数量的字段排序