了解 Scala 中的依赖注入

Understanding DI in Scala

我有两个特点:

trait A {
  def a
}

并且:

trait B { this: A =>
  def b
}

现在,我尝试这样使用 trait B

def method(bTrait: B) = bTrait.a //error

但它拒绝编译。我认为我们可以依赖 B 的任何实现总是扩展 A。怎么了?为什么不能编译?

I thought we could rely on that any implementations of B always extends A

那不是 this: A => 的意思。它的意思是:"in order to use B, I require an instance of A to be provided at compile time"。这可以通过 mixin

来完成

一旦你明白了这一点,你就可以做到:

def method(bTrait: B with A) = bTrait.a