中的特征和抽象方法覆盖

中的特征和抽象方法覆盖

本文介绍了Scala 中的特征和抽象方法覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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().

类似于:

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.

推荐答案

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

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

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

这篇关于Scala 中的特征和抽象方法覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:09