Can't I define defaults if I define multiple overloaded constructors in Scala?

Viewed 3651

I've defined multiple constructors, with some default argument values in all of them. Looks correct (I can't see any ambiguity), but Scala (2.8) compiler complains:

multiple overloaded alternatives of constructor define default arguments

Does it mean that I can't define default values for overloaded constructors at all?

Let me illustrate the situation (primitivized, of course, but illustrative):


class A(subject : Double, factor : Int = 1, doItRight : Boolean = true) {

  def this (subject : Int, factor : Int = 1, doItRight : Boolean = true) = {
    this(subject.toDouble , factor, doItRight)
  }

  def this (subject : String, factor : Int = 1, doItRight : Boolean = true) = {
    this(subject.toDouble , factor, doItRight)
  }

  def this () = {
    this(defaultSubject)
  }

}



3 Answers

Yes, that's not convenient, you'll need to do without default arguments in your auxiliary constructors like:

class X(n: Int, verbose: Boolean = false) {

  def this(n: String, verbose: Boolean) = this(
      Integer.parseInt(n),
      verbose
  )

  def this(n: String) = this(n, false)
}

Mind though that inline (within a function) with default arguments different from each other you can do that:

def main(args: Array[String]): Unit = {

    class Y(n: Int, dummyImplicit: DummyImplicit = null, verbose: Boolean = false) {

        def this(n: String, verbose: Boolean = false) = this(
            Integer.parseInt(n), 
            verbose = verbose
        )
    }
}
Related