简体   繁体   English

伙伴对象会覆盖特征的几种方法

[英]Companion Object override few methods of a trait

So. 所以。 Assume we have a trait Animal 假设我们有一个性格 Animal

trait Animal {
  val typeAnimal: String
  val name: String
}

And now I want to create a class Dog , that extends this trait. 现在,我想创建一个Dog类,以扩展此特征。 But I want to use the Companion Object to override the typeAnimal to Mammal, instead to do it on the class Dog itself. 但是我想使用Companion对象将typeAnimal重写为Mammal,而不是在Dog类本身上进行操作。 Something like 就像是

class Dog(override val name: String) extends Animal
object Dog {
  override val typeAnimal = "Mammal"
}

This doesn't work. 这行不通。 It raises an error saying to me: 它对我说了一个错误:

  1. class Dog doesn't implement typeAnimal Dog类未实现typeAnimal
  2. the override of typeAnimal on the companion object does not override anything 伴随对象上typeAnimal的覆盖不会覆盖任何内容

Is it even possible? 可能吗 Does it have make sense what I'm trying to achieve? 我要达到的目标有意义吗?

EDIT I assume it's not possible to achieve what I'm trying here following Jorg's comment. 编辑我假设按照Jorg的评论无法实现我正在尝试的内容。

What I was trying to do is: a trait define some static value that each class should implement, like typeAnimal, and, since this belongs to all the instance of each class that implements this trait (eg Dog is a mammal, so I don't see any reason why the typeAnimal should be a instance variable instead of a static one) I would like to override in the companion object 我正在尝试做的是:特征定义每个类都应实现的static值,例如typeAnimal,并且由于它属于实现该特征的每个类的所有实例(例如,狗是哺乳动物,所以我不这样做)看不出为什么typeAnimal应该是实例变量而不是静态变量的任何原因)我想在伴随对象中覆盖

If you want typeAnimal to be "static", it shouldn't be a member of the trait itself. 如果要让typeAnimal为“静态”,则它不应该是trait本身的成员。 You can do this instead: 您可以改为:

trait Animal {
  val name: String
  def companion: AnimalCompanion
  // optional: def typeAnimal = companion.typeAnimal
}

trait AnimalCompanion {
  val typeAnimal: String
}

class Dog(override val name: String) extends Animal {
  override def companion = Dog
}
object Dog extends AnimalCompanion {
  override val typeAnimal = "Mammal"
}

The standard library does that with collections . 标准库通过collection来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM