我一直在玩蛋糕模式,还有一些我不完全理解的东西。
给出以下常用代码:
trait AServiceComponent {
this: ARepositoryComponent =>
}
trait ARepositoryComponent {}
以下混合方式的作品
trait Controller {
this: AServiceComponent =>
}
object Controller extends
Controller with
AServiceComponent with
ARepositoryComponent
但以下不是
trait Controller extends AServiceComponent {}
object Controller extends
Controller with
ARepositoryComponent
有错误:
illegal inheritance; self-type Controller does not conform to AServiceComponent's selftype AServiceComponent with ARepositoryComponent
我们不应该能够推动"如果我们知道它们对所有子类都是通用的,那么依赖关系会在层次结构中出现吗?
编译器是否应该允许Controller
具有依赖关系,只要它没有在没有解析它们的情况下实例化?
答案 0 :(得分:3)
这是遇到同样问题的一种稍微简单的方法:
scala> trait Foo
defined trait Foo
scala> trait Bar { this: Foo => }
defined trait Bar
scala> trait Baz extends Bar
<console>:9: error: illegal inheritance;
self-type Baz does not conform to Bar's selftype Bar with Foo
trait Baz extends Bar
^
问题是编译器希望您在子类型定义中重复自我类型约束。在我的简化案例中,我们写道:
trait Baz extends Bar { this: Foo => }
在你的内容中你只需进行以下更改:
trait Controller extends AServiceComponent { this: ARepositoryComponent => }
这个要求是有道理的 - 希望有人使用Controller
能够了解这种依赖关系而不查看它继承的类型是合理的。