【发布时间】:2023-04-04 15:12:01
【问题描述】:
我需要有一个继承自 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)
}
但我需要能够从超类继承所有构造函数,而不支持任何单个超类构造函数。即,我需要String构造函数调用超类的String构造函数。
答案Scala inheritance from Java class: select which super constructor to call 和In Scala, how can I subclass a Java class with multiple constructors? 建议使用特性或由辅助构造函数委托的主构造函数,但这些都不适用于我的场景,因为我需要从可以调用类似的 Java 代码访问:
new HugeDecimal("12.34")
new HugeDecimal(1234)
我有什么解决方案,或者我需要用Java实现这个类吗?
【问题讨论】:
-
为什么不能扩展 Scala 的 BigDecimal?
标签: java scala inheritance constructor multiple-constructors