score:2

the constructor is not any utility function, it is a function that should guarantees that object is fully initialized after it is run.

so if you call car constructor it will return fully initialized car in the process your instance should become fully initialized learninheritance before you start initializing it as car. so you should assume that you can call only one parent constructor.

to deal with this restriction you should require that there is some parent constructor that does all the job, where all other set up some defaults. then you could call that constructor yourself with your constructor that does all the job, and have other constructors act as utilities with defaults.

class foo(name: string, age: int) {

  def this(name: string) = this(name, 10)
  def this(age: int) = this("", age)
}

class bar(name: string, age: int) extends foo(name, age) {
  def this... // bar constructors
}

if you cannot do this, then unfortunately you have to pick only one case in your class.

alternatively, consider that each case is a separate class:

class foo private (name: string, age: int) {

  def this(name: string) = this(name, 10)
  def this(age: int) = this("", age)
}

sealed trait bar { this: foo =>
  // bar methods
}
object bar {
  final class name(name: string) extends foo(name) with bar
  final class age(age: int) extends foo(age) with bar

  def apply(name: string): bar = new name(name)
  def apply(age: string): bar = new age(age)
}

but this has its own issues.

most of the time, though, usage of only one parent constructor for everything is not a problem. if it is then we can think for a solution for a particular case.

score:2

constructors are not instance methods. that means they are not inherited.


Related Query

More Query from same tag