Art*_*ler 5 scala cake-pattern
我一直在玩蛋糕模式,有些事情我还不太了解。
给出以下通用代码:
trait AServiceComponent {
this: ARepositoryComponent =>
}
trait ARepositoryComponent {}
Run Code Online (Sandbox Code Playgroud)
以下将它们混合的方式有效
trait Controller {
this: AServiceComponent =>
}
object Controller extends
Controller with
AServiceComponent with
ARepositoryComponent
Run Code Online (Sandbox Code Playgroud)
但是以下不
trait Controller extends AServiceComponent {}
object Controller extends
Controller with
ARepositoryComponent
Run Code Online (Sandbox Code Playgroud)
错误:
illegal inheritance; self-type Controller does not conform to AServiceComponent's selftype AServiceComponent with ARepositoryComponent
Run Code Online (Sandbox Code Playgroud)
如果我们知道依赖关系对于所有子类都是通用的,我们是否应该不能在层次结构中“推”依赖关系?
Controller
只要编译器不解决不实例化就不应该允许它们具有依赖关系吗?
这是遇到相同问题的稍微简单的方法:
\n\nscala> trait Foo\ndefined trait Foo\n\nscala> trait Bar { this: Foo => }\ndefined trait Bar\n\nscala> trait Baz extends Bar\n<console>:9: error: illegal inheritance;\n self-type Baz does not conform to Bar's selftype Bar with Foo\n trait Baz extends Bar\n ^\n
Run Code Online (Sandbox Code Playgroud)\n\n问题是编译器希望您在子类型定义中重复自类型约束。在我的简化案例中,我们会写:
\n\ntrait Baz extends Bar { this: Foo => }\n
Run Code Online (Sandbox Code Playgroud)\n\n在你的中,你只需要进行以下更改:
\n\ntrait Controller extends AServiceComponent { this: ARepositoryComponent => }\n
Run Code Online (Sandbox Code Playgroud)\n\n这个要求有一定道理\xe2\x80\x94希望使用的人Controller
能够了解这种依赖关系而不用查看它继承的类型是合理的。
归档时间: |
|
查看次数: |
161 次 |
最近记录: |