Search code examples
scalaconstructorabstract-classlanguage-design

What's the use case of secondary constructors in abstract classes?


Consider this code:

abstract class Foo(val s: String) {
  def this(i: Int) = this("" + (i+2))
}

As far as I understand constructors aren't inherited and secondary constructors cannot be called from subclasses with super like in Java.

Are they just a useless artifact or is there some sensible use-case for this construct?


Solution

  • scala> object Bar extends Foo(3)
    defined module Bar
    
    scala> Bar.s
    res3: String = 5