scala:定义特征并引用相应的伴生对象

标签 scala inheritance traits

我正在尝试定义一个使用相应伴随对象的特征,即使用该特征的类的组合对象。

例如,我有:

:paste

class Parent {
  def callMyCompanion = print(Parent.salute)
}

object Parent {
  def salute = "Hello from Parent companion object"
}

class Child extends Parent {

}

object Child {
  def salute = "Hello from Child companion object"
}

然后我创建一个父对象:
scala> val p = new Parent()
p: Parent = Parent@1ecf669

scala> p.callMyCompanion
Hello from Parent companion object

但是有了 child :
scala> val c = new Child()
c: Child = Child@4fd986

scala> c.callMyCompanion
Hello from Parent companion object

我想得到:来自 Child 伴侣对象的你好

我怎样才能实现它???

- 编辑以澄清

感谢您的回复,但在这种情况下,callMyCompanion 是我创建的一个虚拟方法,只是为了解释自己,我试图重用父方法而不必在实现它的每个类中覆盖它......

到目前为止我发现的解决方案是实现一个使用伴随对象的实例方法......

最佳答案

到目前为止,我找到的解决方案是在类中添加对伴随对象的引用,以便每个实例变量都可以访问其类的伴随对象

这样,我只需要覆盖该方法即可获取对伴随对象的引用......

为此,我必须实现一个 ParentCompanion 特性......

但我不需要覆盖 callMyCompanion 或任何其他需要访问伴随对象的方法。

如果我可以通过反射获得伴随对象的引用,一切都会简单得多......

代码是这样的

:paste

trait ParentCompanion {
  def salute: String
}

class Parent {
  def callMyCompanion = print(companion.salute)
  def companion: ParentCompanion = Parent
}

object Parent extends ParentCompanion {
  def salute = "Hello from Parent companion object"
}

class Child extends Parent {
  override def companion = Child
}

object Child extends Companion {
  def salute = "Hello from Child companion object"
}

关于scala:定义特征并引用相应的伴生对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876190/

相关文章:

scala - sbt 编译导致 stackoverflow 错误

c# - 派生子类的集合

C++ 多模板纯虚继承

c++ - 在C++中公开继承其祖 parent 时私下继承 parent

rust - 如何在不消耗值的情况下实现添加特征

scala - 获取 N 的素数列表

scala - 如何在 Scala 中使用逻辑 'OR' 运算符和 "should be"?

scala - 为案例类定义对象

struct - Rust 结构无法替换 HashMap 中的特征

oop - 是否可以从特征内访问结构字段?