Scala trait extending abstract class,如何知道一个抽象方法是否已经实现

Scala trait extending abstract class, how do I know whether an abstract method has been implemented or not

我是scala新手,有以下问题

abstract class A {
    def foo(): List[String]
}

trait AA extends A {
    override def foo(): List[String] = {
        // Something like 
        // If super.foo is implemented, "AA" +: super.foo
        // If super.foo is not implemented, List("AA")
    }
}

class B extends A with AA {
    override def foo(): List[String] = {
        // I think the trait will have the implementation, so I should only need to do:
        super.foo
    }
}

基本上我希望每一个trait在foo的结果上加上一部分,这样我就可以通过混合多个这样的trait来得到最终的结果。我想我可以把 class 中的 foo 方法变成 return 空列表,但我只是好奇是否有办法检查 parent 中的方法是否已经实现。

另外,如果有反模式,请告诉我。

我想你想要 stackable trait pattern

所以你有一个抽象 class A,它声明了一些方法 foo(),你有一个 "decorator" 的那个方法,它说了类似 "I extend A and I would like to append 'AA' to whatever foo() returns".

abstract class A {
  def foo(): List[String]
}

trait AA extends A {
  abstract override def foo(): List[String] = "AA" :: super.foo()
}

注意abstract override,这是关键。它允许我们将一些行为附加到抽象 class.

现在假设我们做这样的事情:

class WithoutImpl extends A with AA {
  override def foo(): List[String] = {
    super.foo() // fails; needs "abstract override" or implementation
  }
}

这失败了,因为每个人都在装修,但没有人真正实施。

让我们添加一个实现特征:

trait AAA extends A {
  override def foo(): List[String] = List("AAA")
}

现在我们可以这样做:

class WithImpl extends AA with AAA {
  def myFoo(): List[String] = {
    super.foo() // error! wrong order of initialization
  }
}

由于 mixins 的顺序,这仍然会失败。我们必须首先提供一个实现,然后我们提供装饰器,然后装饰器将继续添加行为。

class WithImpl extends AAA with AA  {
  def myFoo(): List[String] = {
    super.foo() // works!
  }
}

println((new WithImpl().myFoo())) // List("AA", "AAA")

你可以添加任意数量的装饰器,只需要注意顺序即可。例如。如果我们有 BBCC 类似于 AA,我们可以这样做:

class WithImpl extends AAA with AA with BB with CC  {
  def myFoo(): List[String] = {
    super.foo() // List(CC, BB, AA, AAA)
  }
}