如何让相同基本特征的多个特征实现相同的方法 [英] How to have multiple traits of same base trait implement the same method

查看:39
本文介绍了如何让相同基本特征的多个特征实现相同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,其中包含从固定基本特征继承的多个特征.基本 trait 有一个抽象方法,每个人都需要实现.使用这些traits的类也需要实现这个方法:

I have a scenario with multiple traits inheriting from a fixed base trait. The base trait has an abstract method that each needs to implement. The class using these traits also needs to implement this method:

trait A {
    def f: Any
}

trait B1 extends A {
    val i: Int
    override def f: Any = println("B1: " + i)        
}

trait B2 extends A {
    val j: Int
    override def f: Any = println("B2: " + j)
}

class C extends A with B1 with B2 {
    val i = 1
    val j = 2

    override def f: Any = {
        super.f
        println("C::f")
    }
}

然后当我做一个

new C().f

它只输出B1:1"而不输出B2:2"

It only outputs "B1: 1" and not "B2: 2"

有没有一种方法可以定义 B1、B2 和 C,以便可以调用 f 的所有实现?

Is there a way I can define B1, B2 and C so that all implementations of f can be called?

推荐答案

你知道你混入了哪两个菱形特征,你可以调用这两个 super 实现并指定你想要的特征调用每个 super 实现.

Well as you know which two diamond traits you mix in, you can call both super implementations and specify the trait from which you want to call each super implementation.

所以,你可以像这样实现 C:

So, you could implement C like this:

class C extends A with B1 with B2 {
  val i = 1
  val j = 2

  override def f: Any = {
    super[B1].f
    super[B2].f
    println("C::f")
  }
}

并会得到输出:

B1: 1
B2: 2
C::f

这篇关于如何让相同基本特征的多个特征实现相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆