2017-10-04 48 views
0

我有2个特征和1个类。无法重写Scala中的方法

在特质A,这两种方法A1A2需要执行

scala> trait A { 
    | def A1 
    | def A2 
    | } 
defined trait A 

在特质B,即使A1在这里实现,它需要是抽象的,因为它使用的超级,它仍然需要实例类实现。 A2实现

scala> trait B extends A { 
    | abstract override def A1 = { 
    | super.A1 
    | } 
    | def A2 = println("B") 
    | } 
defined trait B 

现在我有一个类C定义A1(不涉及以前的性状)

scala> class C { 
    | def A1 = println("C") 
    | } 
defined class C 

现在我要创建的对象C1这应该是C型的,但我想一些功能B以及(如A2)。但它不编译。我如何使用A2 from B in C?我认为它会工作,因为C已经实施A1

scala> val c1 = new C with B 
<console>:13: error: overriding method A1 in class C of type => Unit; 
method A1 in trait B of type => Unit cannot override a concrete member without a third member that's overridden by both (this rule is designed to prevent ``accidental overrides'') 
     val c1 = new C with B 
        ^

回答

3

该错误阻止您这样做以防止“意外覆盖”。您的A1方法在BC中都有定义,但是对于编译器来说,它们不相关,只是恰好具有相同的类型签名。因此,您必须在您的对象中提供此方法的重写实现。你可以这样做:

val c1 = new C with B { 
    override def A1 = ??? // Add your implementation here. 
}