伴侣对象可用于存储类的所有实例共有的状态和方法,但它们不使用静态方法或字段。他们使用可以通过继承重写的常规虚拟方法。Scala确实没有什么静态的。您可以使用多种方式使用此功能,但这是一个简单的示例。abstract class AnimalCounter{ var animals = 0 def name: String def count() { animals += 1 println("%d %ss created so far".format(animals, name)) }}abstract class Animal{ def companion: AnimalCounter companion.count()}object Dog extends AnimalCounter{ val name = "dog"}class Dog extends Animal{ def companion = Dog}object Cat extends AnimalCounter{ val name = "cat"}class Cat extends Animal{ def companion = Cat}产生以下输出:scala> new Dog1 dogs created so farscala> new Cat1 cats created so farscala> new Dog2 dogs created so farscala> new Cat2 cats created so far