If I have a case class that inherits another class like this
class Person(name: String) {
}
case class Male() extends Person("Jack") {
def f = super.name // Doesn't work
}
How to get the name property from Male class ?
If I have a case class that inherits another class like this
class Person(name: String) {
}
case class Male() extends Person("Jack") {
def f = super.name // Doesn't work
}
How to get the name property from Male class ?
class Person(name: String) {
In this declaration, name
is not a field of the class, it is just a constructor parameter. So it is accessible inside the constructor, but not outside (including in a subclass). You can make it a field by making it a val
:
class Person(val name: String) {
Confusingly, constructor parameters for a case class
are also fields even without val
Try to make name
a val
(or at least protected val
) in Person
, then it will be accessible in Male
class Person(val name: String)
case class Male() extends Person("Jack") {
def f = name
}
When you wrote class Person(name: String)
you actually created class Person(private[this] val name: String)
so name
was not accessible in Male
.