@xtccc
2016-03-11T10:18:49.000000Z
字数 1151
阅读 2391
Scala
目录:
在定义trait时,可以看到如下的写法:
trait CorsDirectives {
this: HttpService =>
def f(origin: String) = ...
val x = ...
}
这里的this是啥意思呢?
这是关于 Dependency Injection 的一种用法,比方说 Cake Pattern 模式。 这篇文档 涵盖了Scala中关于dependency injection的多种形式。
实际上,这里我们碰到的this: HttpService =>
实际上就是self type annotation,可以参考 Scala Self Types by Gregor Heine, Principal Software Engineer at Gilt 。
首先看一个抽象的形式:
trait A { ... }
trait B { ... }
trait C {
this: A => // self type
...
}
trait D {
this: A with B => // multiple dependencies
...
}
trait E {
a: A => // `this` can be replaced with other variable names
}
class X extends C with A {
...
}
class Y extends C {
this: A =>
...
}
class Z extends D with A with B {
...
}
关于Self Type的解释:
A self type of a trait is the assumed type of this, the receiver, to be used within the trait. Any concrete class that mixes in the trait must ensure that its type conforms to the traits's self type.
- Self types are used with traits
- Explicitly declare the type of the value this
- Specify the requirements on any concrete class or instance the trait is mixed into
- Declare a dependency of the trait on another type: "In order to use me you have to be one of those"
在 Github 上有一个具体的实例代码。
通过第2小节的解释,可以看出,self type实际上是要求一个trait依赖于另一种trait,这就是dependency injection。