我是 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
}
}
基本上,我希望每个特征在foo的结果中添加一部分,这样我就可以通过混合多个这样的特征来获得最终结果。我想我可以使类 A 中的 foo 方法返回空列表,但我只是好奇是否有办法检查父级中的方法是否已实现。
另外,如果有反模式,请告诉我。
我认为你想要可堆叠的特征模式。
所以你有一个抽象类A
它声明了一些方法foo()
,并且你有一个该方法的"装饰器",他说"我扩展A
,我想将'AA'附加到任何foo()
返回的东西"。
abstract class A {
def foo(): List[String]
}
trait AA extends A {
abstract override def foo(): List[String] = "AA" :: super.foo()
}
请注意abstract override
,这是关键。它允许我们将一些行为附加到抽象类中。
现在假设我们做这样的事情:
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
}
}
由于混合的顺序,这仍然会失败。我们必须首先提供一个实现,然后我们提供装饰器,然后他们将继续添加行为。
class WithImpl extends AAA with AA {
def myFoo(): List[String] = {
super.foo() // works!
}
}
println((new WithImpl().myFoo())) // List("AA", "AAA")
您可以根据需要添加任意数量的装饰器,只需注意顺序即可。 例如,如果我们有类似于AA
BB
和CC
,我们可以做:
class WithImpl extends AAA with AA with BB with CC {
def myFoo(): List[String] = {
super.foo() // List(CC, BB, AA, AAA)
}
}