Search code examples
scalainheritancedefault-parameters

Scala inheritance default parameter in parent class


I have an abstract class with a default value for its parameter. I don't want to have to reuse the default value in the constructor of all the possible implementations.

abstract class Place(val place: String = "World")
class Message(val message: String = "Hello", p: String) extends Place(p) {
    override def toString = s"$message $place"
}

What I want to get

new Message("Hi", "Universe") = "Hi Universe" // Ok
new Message("Hi") = "Hi World" // Doesn't work, second parameter is required
new Message() = "Hello World" // Doesn't work, second parameter is required

I considered using an auxiliary constructor omitting the second parameter, but it doesn't help since you can't call super constructors outside of the main constructor.

I want to know how to do it, or why it is not possible. I'm not looking for a workaround, like not using inheritance.


Solution

  • You can reuse the default value in a more elegant way:

    object Place {
      val defaultPlace = "World"
    }
    abstract class Place(val place: String = Place.defaultPlace)
    class Message(val message: String = "Hello", p: String = Place.defaultPlace) extends Place(p) {
      override def toString = s"$message $place"
    }