我需要一个从 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 call和 In 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/