tags:

views:

101

answers:

3

I wonder if it is possible to inherit auxiliary constructors in Scala?

I tested this code, and it complained

temp.scala:18: error: too many arguments for constructor Child: ()this.Child

val a = new Child(42)

   ^
abstract class Father {
 var value: Int = 0

 protected def setValue(v: Int) = {
  value = v
 }

 protected def this(v: Int) = {
  this()
  setValue(v)
 }
}

class Child extends Father {
}

val a = new Child(42)

But if i put

protected def this(v: Int) = {
    this()
    setValue(v)
}

in the Child class, everything is all right.

+1  A: 

No.

missingfaktor
You should provide a link to somewhere that says why this is so. My lack of knowledge of Scala – and so inability to select a good link – was why I didn't turn my (slightly facetious) comment into an answer…
Donal Fellows
+1  A: 

Your Child constructor have no parameter and you are trying to instanciate it with one ! You have to declare a parameter in your Child constructor and then pass it to the Father class, for example:

class Child(v:Int) extends Father(v) {
}

val a = new Child(42)
Patrick
+1  A: 

Absolutely not, and your example demonstrates why. You've introduced a mutable variable value that may or may not be initialised - depending on the exact constructor used.

This is a potential source for a great many problems, and so Scala made the decision that all object creation should ultimately be directed via the primary constructor, this ensuring consistent initialisation.

If you want value to have a default value, then you can specify it as a default parameter (in 2.8+):

abstract class Father(val value : Int = 0)

or you can use the auxiluary constructor to achieve the same effect in Scala 2.7:

abstract class Father(val value : Int) {
  def this() = this(0)
}

With Father defined in either of the above ways, the following definitions of child are both valid:

class Child(v:Int) extends Father(v)

class Child extends Father()

You can also make value a var if you absolutely have to, but I strongly advise against it.

If the semantics of value mean that it's valid to not be initialised, then the correct Scala idiom is to declare it as Option[Int]:

abstract class Father(val value : Option[Int] = Some(0))
Kevin Wright