【问题标题】:Scala inheritance of Java constructorsJava构造函数的Scala继承
【发布时间】: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 callIn 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


【解决方案1】:

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

【讨论】:

  • 问题是不能继承构造函数。问题是我需要能够选择要委托给哪个超类构造函数。
  • 那你为什么不能选择呢?
  • String构造函数需要委托给超类的String构造函数,Int构造函数需要委托给超类的int构造函数。那可能吗?如果是这样,我很乐意看到一个例子。
  • 好的,我明白你现在的意思了......好吧,你可以从java代码中调用这样的东西:HugeDecimal.apply("12.34")(如果HugeDecimal是一个对象并且没有“companion”,则此方法有效" class ... 否则,您必须这样做 HugeDecimal$.MODULE$.apply("12.34") )。然后您可以使用您引用的答案中描述的方法之一 - 基本上,使用特征来扩展,并使用对象 apply 方法来调用正确的构造函数。
猜你喜欢
  • 2013-03-21
  • 2011-09-09
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多