Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法重写Scala中的方法_Scala - Fatal编程技术网

无法重写Scala中的方法

无法重写Scala中的方法,scala,Scala,我有两个特点和一个阶级 在traitA中,两种方法A1和A2都需要实现 scala> trait A { | def A1 | def A2 | } defined trait A 在traitB中,尽管这里实现了A1,但它需要抽象,因为它使用super,并且仍然需要在实例类中实现A2已实现 scala> trait B extends A { | abstract override def A1 = { | super.A1

我有两个特点和一个阶级

在trait
A
中,两种方法
A1
A2
都需要实现

scala> trait A {
     | def A1
     | def A2
     | }
defined trait A
在trait
B
中,尽管这里实现了
A1
,但它需要抽象,因为它使用super,并且仍然需要在实例类中实现<代码>A2已实现

scala> trait B extends A {
     | abstract override def A1 = {
     | super.A1
     | }
     | def A2 = println("B")
     | }
defined trait B
现在我有了一个类
C
,它定义了
A1
(与以前的特征无关)

现在我想创建对象
C1
,它应该是
C
类型,但我也想要
B
的一些功能(比如
A2
)。但它没有编译。如何在
C
中使用
B
中的
A2
?我认为它会起作用,因为
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
                    ^
scala>val c1=带B的新C
:13:错误:重写类型=>Unit的C类中的方法A1;
type=>Unit的trait B中的方法A1不能在没有第三个成员的情况下重写一个具体成员,而第三个成员被这两个成员都重写(此规则旨在防止“意外重写”)
val c1=带B的新C
^

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

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

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

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