假设我有两个特征(A和B)和一个C类混合它们并实现它们的方法:
trait A {
def foo
}
trait B {
def bar
}
class C extends A with B {
def foo = "Foo"
def bar = "Bar"
}
Run Code Online (Sandbox Code Playgroud)
在Scala中是否有任何方法可以指定扩展特征B的类必须扩展特征A然后在特征B中使用特征A定义方法的实现方法?
那么B可以调用this.foo()并访问C实现返回的值吗?
只需指定您想要的内容this:
trait B { this: A =>
def bar = this.foo
}
Run Code Online (Sandbox Code Playgroud)
这就是所谓的自我类型,this这里是别名而不是关键字(所以自我:A,即:A等等是完全合法的).
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |