强制Scala trait实现特定方法

4

有没有一种方法可以指定trait必须提供一个具体的方法实现?

给定一些mixin:

class A extends B with C {
  foo()
}

如果ABC实现了foo(),程序将编译通过。但是,我们如何强制要求例如B包含foo的实现呢?
1个回答

10

您可以进行以下操作:

class A extends B with C {
  super[B].foo()
}

只有当 B 实现了 foo 时,此代码才会被编译。然而要小心使用,因为它(潜在地)引入了一些不直观的耦合。此外,即使 A 覆盖了 fooBfoo 仍将被调用。

我认为一个有效的用例是解决冲突问题

trait B { def foo() = println("B") }
trait C { def foo() = println("C") }
class A extends B with C {
  override def foo() = super[B].foo()
}

如果您想确保B声明了foo,您可以使用类型注释:

(Note: The translated text is the result of polishing and simplifying the original content without altering its meaning, while preserving HTML tags. No additional explanations are provided.)
class A extends B with C {
  (this:B).foo()
}

只有当B 声明foo时,这段代码才会编译通过(但它可能是在CA中实现的)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接