Question

Is it possible to define constructor signature in Scala ?

abstract class A {
    def this (s: String): this.type // doesn't work
    def this (i: Int): this.type    // doesn't work
    def this (d: Double): this.type // doesn't work
}

class B(var s: String) extends A {
    def this(i: Int) = {
        this("int "+i.toString())
    }
    def this(d: Double) = {
        this("double "+d.toString())
    }
}
Was it helpful?

Solution 2

You can't do exactly what you want, as pointed out by other answer, but one approach is to use a factory:

trait Foo { 
  // methods you need
}

trait FooCompanion[T <: Foo] {
  // these methods replace constructors in your example
  def apply(s: String): T
  def apply(i: Int): T
  ...
}

Implementation:

class Bar(s: String) extends Foo {
  ...
}

object Bar extends FooCompanion[Bar] {
  def apply(s: String) = new Bar(s)
  ...
}

and you can have methods taking FooCompanion. This pattern is used e.g. in the Scala collections library.

OTHER TIPS

What are you trying to achieve? You can do like this:

abstract class A(i: Int)

case class B(s: String) extends A(s.toInt) {
  def this(i: Int) = {
    this(i.toString)
  }

  def this(d: Double) = {
    this(d.toString)
  }
}

Usage:

B("1")
new B(1)
new B(1.0)

No that is not possible. Constructors are special: You need to write new X() instead of X(), and there is no polymorphic dispatch, e.g. you cannot do def test[A]() = new A(). So there is no scenario in which an abstract constructor would make any sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top