0

If I have a trait :

 trait Person
 {
    val name: String
 }

and then a case class:

 case class Student(val name: String) extends Person
 {
     ......   
 }

Are these two "name" the same thing? If I pass a value to Student's "name" field, can I access to this value through Person's name? I guess not. Or Student's "name" overrides Person's name? I guess I can only access Student's name via the Student class.

User0123456789
  • 760
  • 2
  • 10
  • 25
jlp
  • 1,656
  • 6
  • 33
  • 48

1 Answers1

1

You are overriding the abstract field in the Person trait with a field in your Student class, so your guess is correct.

You might want to consider some small changes. You could make the abstract definition in the trait a "def". That gives you more flexibility in overriding, see https://stackoverflow.com/a/19642301/52055

Also, in case classes, the "val" keyword is assumed for your class parameters, so you don't need to provide it. So you'd end up with

 trait Person
 {
    def name: String
 }

 case class Student(name: String) extends Person
 {
     ......   
 }
Community
  • 1
  • 1
lutzh
  • 4,917
  • 1
  • 18
  • 21
  • Thank you. So in order to access name from Person, i have to do something like Person.name = Student.name ? – jlp Mar 29 '16 at 17:48
  • No. Or rather, not sure I understand what you mean. If you have a method that expects a Person, say "p", it's fine to say p.name. The actual implementation you get can be a student, or anything else that implements the Person trait. – lutzh Mar 30 '16 at 10:35