Scala: how to inherit a “static slot”?

前端 未结 4 682
鱼传尺愫
鱼传尺愫 2021-01-05 09:33

Well, I\'m learning Scala so this question may be too basic for most people.

In Java I can have a static slot (function or variable) in a class, and then I will have

4条回答
  •  感情败类
    2021-01-05 10:18

    Afaics, Daniel Spiewak's and Walter Chang's answers appear to provide two separate copies of the all list. I didn't test the following, but I hope this provides the correct outline even it if has errors.

    class Person
    class Student extends Person
    
    object Person {
      val all: List[Person]
    }
    

    then within Student, access via Person.all

    If you want to provide access via Student.all then

    object Student {
      def all() = Person.all
    }
    

    Another way to do it, would allow you to declare the statics (i.e singleton object) in a trait to be inherited.

    trait StaticAll {
       object Static { val all: List[Person] }
    }
    
    class Person extends StaticAll
    class Student extends Person
    

    Then access with StaticAll#Static.all. I think that is correct and not StaticAll.Static.all. Again this is all off the top of my head, I didn't test any this. Please correct my errors.

提交回复
热议问题