Scala: how to inherit a “static slot”?

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

    I don't know if this is what you meant, but a companion object can extend from some traits/classes:

    class Person
    class Student extends Person
    
    trait Aggregation[T] {
      val all: List[T]
    }
    
    object Person extends Aggregation[Person] {
      val all: List[Person] = List(new Person, new Person)
    }
    
    object Student extends Aggregation[Student] {
      val all: List[Student] = List(new Student, new Student)
    }
    
    println(Person.all) // prints all persons
    println(Student.all) // prints all students
    

提交回复
热议问题