我一直在玩蛋糕模式,有一些我不太了解的东西.
鉴于以下常见代码:
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具有依赖关系,只要它没有实例化而不解析它们?
解决方法
这是一个稍微简单的方法来遇到同样的问题:
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能够知道这种依赖关系而不查看它继承的类型是合理的.