蛋糕图案:特质融合

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只要编译器不解决不实例化就不应该允许它们具有依赖关系吗?

Tra*_*own 4

这是遇到相同问题的稍微简单的方法:

\n\n
scala> 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\n
trait Baz extends Bar { this: Foo => }\n
Run Code Online (Sandbox Code Playgroud)\n\n

在你的中,你只需要进行以下更改:

\n\n
trait Controller extends AServiceComponent { this: ARepositoryComponent => }\n
Run Code Online (Sandbox Code Playgroud)\n\n

这个要求有一定道理\xe2\x80\x94希望使用的人Controller能够了解这种依赖关系而不用查看它继承的类型是合理的。

\n