Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Can you overload a constructor with more than just a one-line constructor?

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)
}
like image 698
socom1880 Avatar asked Oct 19 '22 15:10

socom1880


1 Answers

You can rewrite as follows:

def this(num: Int) =
  this{
    val numAsString = num.toString
    numAsString
  }
like image 114
Seth Tisue Avatar answered Oct 27 '22 10:10

Seth Tisue