9
votes

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

} 
4

4 Answers

10
votes

The input parameters for the constructor are not vals unless you say they are. And if they are already, why override them?

class Person(val firstName: String, val lastName: String) {}
class Strange(
  override val firstName: String, override val lastName: String
) extends Person("John","Doe") {}
class Employee(fn: String, ln: String, val depart: String) extends Person(fn,ln) {}

If they're not vals and you want to make vals, you don't need to override:

class Person(firstName: String, lastName: String) {}
class Employee(
  val firstName: String, val lastName: String, val depart: String
) extends Person(firstName,lastName) {}
7
votes

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.

2
votes

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
0
votes

Unless I've misunderstood your intention, here's how to extend Person.

Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Person( firstName: String, lastName: String)
defined class Person

scala> class Employee(firstName: String, lastName: String, depart: String) extends Person(firstName, lastName)
defined class Employee