[关闭]
@xtccc 2016-03-11T02:18:49.000000Z 字数 1151 阅读 2258

Self Type Annotation

给我写信
GitHub

此处输入图片的描述

Scala



目录:


1. 引子


在定义trait时,可以看到如下的写法:

  1. trait CorsDirectives {
  2. this: HttpService =>
  3. def f(origin: String) = ...
  4. val x = ...
  5. }

这里的this是啥意思呢?

这是关于 Dependency Injection 的一种用法,比方说 Cake Pattern 模式。 这篇文档 涵盖了Scala中关于dependency injection的多种形式。

实际上,这里我们碰到的this: HttpService =>实际上就是self type annotation,可以参考 Scala Self Types by Gregor Heine, Principal Software Engineer at Gilt




2. Self Type


首先看一个抽象的形式:

  1. trait A { ... }
  2. trait B { ... }
  3. trait C {
  4. this: A => // self type
  5. ...
  6. }
  7. trait D {
  8. this: A with B => // multiple dependencies
  9. ...
  10. }
  11. trait E {
  12. a: A => // `this` can be replaced with other variable names
  13. }
  14. class X extends C with A {
  15. ...
  16. }
  17. class Y extends C {
  18. this: A =>
  19. ...
  20. }
  21. class Z extends D with A with B {
  22. ...
  23. }



关于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 上有一个具体的实例代码。



3. Dependency Injection


通过第2小节的解释,可以看出,self type实际上是要求一个trait依赖于另一种trait,这就是dependency injection。




添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注