5

Is there a way to overload a constructor with more than just a one-line constructor? It seems like putting any more than one statement in an overloaded constructor gives the error Application does not take parameters. For example, if the primary constructor take a String, the following will work:

def this(num: Int) = {
  this(num.toString())
}

The following, however, will not:

def this(num: Int) = {
  val numAsString = num.toString()
  this(numAsString)
}
socom1880
  • 340
  • 3
  • 12
  • Possibly relevant question: http://stackoverflow.com/questions/2400794 – socom1880 Feb 22 '16 at 20:36
  • Why should `val hi` be the first line? You can always make the super call the first statement. Can you elaborate your example. It is unclear what you are trying to achieve. – 0__ Feb 22 '16 at 20:56
  • 1
    s/can always/must always, s/super call/self constructor invocation. `A constructor expression is either a self constructor invocation this(args1)…(argsn) or a block which begins with a self constructor invocation.` – som-snytt Feb 22 '16 at 21:56
  • Updated for clarity. @som-snytt where are you getting that from? Do you know why that would be the case? It seems that if the first example in my question is possible, the second should be as well. Does this mean that any computations that happen for an overloaded constructor need to be single expressions and cannot assign interstitial `val`s? – socom1880 Feb 22 '16 at 22:36
  • It's from the Scala Language Specification, section 5.3.1: http://www.scala-lang.org/files/archive/spec/2.11/05-classes-and-objects.html#constructor-definitions – Seth Tisue Feb 22 '16 at 22:57
  • 3
    Possible duplicate of [Why can auxiliary constructors in Scala only consist of a single call to another constructor?](http://stackoverflow.com/questions/14207989/why-can-auxiliary-constructors-in-scala-only-consist-of-a-single-call-to-another) – Bergi Feb 22 '16 at 23:09

1 Answers1

3

You can rewrite as follows:

def this(num: Int) =
  this{
    val numAsString = num.toString
    numAsString
  }
Seth Tisue
  • 29,985
  • 11
  • 82
  • 149
  • Is it possible to call constructors with multiple parameters like that? E.g. could one write `this(num.toString, num.toString)` with only a single `toString` invocation? – Bergi Feb 22 '16 at 22:49
  • No. See http://stackoverflow.com/a/14210930/86485 for a fuller discussion of this. – Seth Tisue Feb 22 '16 at 22:55
  • Thanks, that clears everything up - and indeed a factory (without `new`) seems cleaner here anyway. Btw, isn't that an exact duplicate? – Bergi Feb 22 '16 at 23:10