Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must override val variable in scala

Tags:

scala

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){

} 
like image 602
zjffdu Avatar asked Jun 03 '11 06:06

zjffdu


2 Answers

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.

like image 91
Dirk Avatar answered Sep 28 '22 07:09

Dirk


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
like image 42
Sam Stainsby Avatar answered Sep 28 '22 09:09

Sam Stainsby