dra*_*wka 5 scala cake-pattern
我正在尝试使用像这样的蛋糕模式进行依赖注入:
trait FooComponent {
val foo: Foo
trait Foo;
}
trait AlsoNeedsFoo {
this: FooComponent =>
}
trait RequiresFoo {
this: FooComponent =>
val a = new AlsoNeedsFoo with FooComponent{
val foo: this.type#Foo = RequiresFoo.this.foo
}
}
Run Code Online (Sandbox Code Playgroud)
但编译器抱怨RequiresFoo.this.type#Foo说它不符合预期的类型this.type#Foo.
所以问题是:是否可以在AlsoNeedsFoo内部创建一个对象,RequiresFoo以便依赖注入正常工作?
使用蛋糕模式,您不应该实例化其他组件,而是扩展它们.
在你的情况下,如果你需要功能,AlsoNeedsFoo你应该写这样的东西:
this: FooComponent with AlsoNeedsFoo with ... =>
Run Code Online (Sandbox Code Playgroud)
并将所有内容放在最顶层:
val app = MyImpl extends FooComponent with AlsoNeedsFoo with RequiresFoo with ...
Run Code Online (Sandbox Code Playgroud)