Scala 中的特征和抽象方法覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2038370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:50:53  来源:igfitidea点击:

Traits and abstract methods override in Scala

scalatraits

提问by IttayD

I have a base abstract class (trait). It has an abstract method foo(). It is extended and implemented by several derived classes. I want to create a trait that can be mixed into the derived classes so that it implements foo()and then calls the derived class's foo().

我有一个基本抽象类(特征)。它有一个抽象方法foo()。它由几个派生类扩展和实现。我想创建一个可以混合到派生类中的特征,以便它实现foo()然后调用派生类的foo().

Something like:

就像是:

trait Foo {
  def foo()
}

trait M extends Foo {
  override def foo() {
    println("M")
    super.foo()
  }
}

class FooImpl1 extends Foo {
  override def foo() {
    println("Impl")
  }
}

class FooImpl2 extends FooImpl1 with M 

I tried self types and structural types, but I can't get it to work.

我尝试了自我类型和结构类型,但我无法让它工作。

回答by retronym

You were very close. Add the abstract modifier to M.foo, and you have the 'Stackable Trait' pattern: http://www.artima.com/scalazine/articles/stackable_trait_pattern.html

你非常接近。将抽象修饰符添加到 M.foo,您将拥有“可堆叠特征”模式:http: //www.artima.com/scalazine/articles/stackable_trait_pattern.html

trait Foo {
  def foo()
}

trait M extends Foo {
  abstract override def foo() {println("M"); super.foo()}
}

class FooImpl1 extends Foo {
  override def foo() {println("Impl")}
}

class FooImpl2 extends FooImpl1 with M