Scala: how to inherit a “static slot”?

前端 未结 4 715
鱼传尺愫
鱼传尺愫 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:35

    Objects in Scala are not class-level entities like statics are in Java. They are simply a class definition and singleton instantiation rolled into one.

    A companion object is a special case that allows the sharing of private data between it and its companion class.

    Objects can extend classes, but not other objects. After all an 'object' is just a singleton instance - the class definition of an 'object' is hidden.

    Is it reasonable to expect the special relationship between companion objects and companion classes to project an additional class hierarchy on companion objects?

    I suspect the best way to achieve a dependency between Person and Student is to delegate.

    object Person { val all = List(1,2,3) }
    object Student { val all = Person.all.filter(_ % 2 == 0) }
    

提交回复
热议问题