I meet a weird problem in scala. Following is my code, class Employee extends class Person
But this piece of code can not been compiled, I have explicit define firstName and lastName as val variable. Why is that ? Does it mean I have to override val variable in base class ? And what is the purpose ?
class Person( firstName: String, lastName: String) {
}
class Employee(override val firstName: String, override val lastName: String, val depart: String)
extends Person(firstName,lastName){
}
Since the constructor arguments have no val/var declaration in Person, and as Person is no case class, the arguments will not be members of class Person, merely constructor arguments. The compiler is telling you essentially: hey, you said, that firstName and lastName are members, which override/redefine something inherited from a base class - but there is nothing as far as I can tell...
class Person(val firstName: String, val lastName: String)
class Employee(fn: String, ln: String, val salary: BigDecimal) extends Person(fn, ln)
You do not need to declare firstName/lastName as overrides here, btw. Simply forwarding the values to the base class' constructor will do the trick.
You might also consider redesigning your super classes as traits as much as possible. Example:
trait Person {
def firstName: String
def lastName: String
}
class Employee(
val firstName: String,
val lastName: String,
val department: String
) extends Person
or even
trait Employee extends Person {
def department: String
}
class SimpleEmployee(
val firstName: String,
val lastName: String,
val department: String
) extends Employee
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