In Scala, how can I extend a trait in a class with private constructor parameter that is defined in the trait?
trait Parent {
protected def name: String
require(name != "", "wooo problem!")
}
class Child(private val name: String) extends Parent {
println("name is " + name)
}
The above class gives an error:
class Child needs to be abstract, since method name in trait Parent of type ⇒ String is not defined.
Of-course I can:
- make the
Child
class abstract, - define it without using the private in the constructor like
class Child(val name: String)
. - make the Parent an
abstract class
instead of a trait
But with the above implementation, is there no way I can have a private constructor parameter while extending a trait? Note that I want the variable to be private so that I should not be able to do childInstance.name
.
protected
and change the child constructor toChild(name: String)
, I cannot access the variable outside. This is good enough for me! – rgamberclass Child{ private val name = "" }
? – nmat