加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 10:08:18 所属栏目:安全 来源:网络整理
导读:我正在尝试定义一个使用相应伴随对象的特征,即使用特征的类的componion对象. 例如,我有: :pasteclass Parent { def callMyCompanion = print(Parent.salute)}object Parent { def salute = "Hello from Parent companion object"}class Child extends Paren
我正在尝试定义一个使用相应伴随对象的特征,即使用特征的类的componion对象.

例如,我有:

: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

但是带着孩子:

scala> val c = new Child()
c: Child = Child@4fd986

scala> c.callMyCompanion
Hello from Parent companion object

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

我怎么能实现呢???

– 编辑澄清

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

到目前为止我找到的解决方案是实现一个使用伴侣obejct的实例方法……

解决方法

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

这样,我只需要覆盖方法来获取对伴随对象的引用…

要做到这一点,我必须实现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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读