Scala inheritance of Java constructors

401 Views Asked by At

I need to have a Scala class HugeDecimal that inherit from java.math.BigDecimal. It cannot be a trait for internal reasons. The following simple implementation:

class HugeDecimal extends java.math.BigDecimal {
}

Raises this error:

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

I know I can do:

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

But I need to be able to inherit all the constructors from the superclass without favoring any single superclass constructor. I.e., I need to the String constructor call the superclass' String constructor.

The answers Scala inheritance from Java class: select which super constructor to call and In Scala, how can I subclass a Java class with multiple constructors? suggest using traits or a primary constructor that is delegated to by auxiliary constructors, but neither of these works for my scenario, since I need to be accessible from Java code that can call things like:

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

I there any solution, or do I need to implement this class in Java?

1

There are 1 best solutions below

4
On

You cannot inherit constructors. It does not matter if you implement it in java or in scala, if you want to have several constructors, you will have to implement each one of them.