特质A只能通过扩展特征B的类扩展

时间:2013-07-22 15:13:09

标签: scala traits

假设我有两个特征(A和B)和一个C类混合它们并实现它们的方法:

trait A {
    def foo
}

trait B {
    def bar
}    

class C extends A with B {
    def foo = "Foo"
    def bar = "Bar"
}

在Scala中是否有任何方法可以指定扩展特征B的类必须扩展特征A然后在特征B中使用特征A定义方法的实现方法?

这样B可以调用this.foo()并访问C实现返回的值吗?

1 个答案:

答案 0 :(得分:5)

只需指定您想要的this

trait B { this: A =>
  def bar = this.foo
}

这就是所谓的自我类型this这里是别名而不是关键字(所以自我:A,即:A等完全合法)。