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:
Child
class abstract, class Child(val name: String)
. abstract class
instead of a traitBut 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
.
Try this
trait Parent {
protected def name: String
require(name != "", "wooo problem!")
}
class Child(override protected val name: String) extends Parent {
val publicVar = "Hello World"
println("name is " + name)
}
def main(args: Array[String]): Unit = {
val child = new Child("John Doe")
println(child.publicVar)
println(child.name) // Does not compile
}
You will not be able to access to child.name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With