pygumby
pygumby

Reputation: 6790

How to not override a val of a parent class?

please take a look at the following code:

scala> sealed abstract class Person(val name: String)
defined class Person

scala> case class Student(id: Int, name: String) extends Person(name)
<console>:8: error: overriding value name in class Person of type String;
value name needs `override' modifier
       case class Student(id: Int, name: String) extends Person(name)
                                   ^

This might be a trivial question, but after searching the web for quite some time, I wasn't able to figure out how to simply pass the string that Student's constructor will be provided as name to the Person's constructor. I don't want to override anything. What am I doing wrong?

Thank you very much in advance!

Upvotes: 0

Views: 101

Answers (1)

Dima
Dima

Reputation: 40500

All constructor parameters of a case class are vals. That's the whole point. Roughly speaking, it is what gives you the ability to enjoy the benefits cases classes provide compared to regular classes: copying, extraction, pattern matching, etc.

If you want Student to be a case class, you should override name. Theoretically, you can avoid overriding it by giving the val a different name: case class Student(id: Int, studentName: String) extends Person(studentName) - this works, but just doesn't make very much sense - you end up having two different member vals whose values are always identical.

Alternatively, if there is an actual reason why you don't want to override name (I can't imagine what one could possibly be, but if ...), then Student should not be a case class: class Student(val id: Int, name: String) extends Person(name).

Upvotes: 2

Related Questions