scala - 蛋糕图案 : mixing in in a trait

标签 scala cake-pattern

我一直在玩蛋糕图案,有些东西我不完全理解。

给定以下通用代码:

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 是合理的。无需查看它继承的类型即可了解此依赖项。

关于scala - 蛋糕图案 : mixing in in a trait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22662406/

相关文章:

scala - SBT 解析器在 build.sbt 中工作,在 Build.scala 中不起作用

scala - spark中 "grouped"的替代

scala - 在 Scala 中巧妙地处理 Option[T]

Scaladoc 无法为方法和类签名中的内部类生成链接

java - Java8 的蛋糕模式可能吗?

scala - 如何指示结果为空的函数失败

algorithm - Apache Spark - 处理时态 RDD 上的滑动窗口

scala - 如何使用 Scala 的蛋糕模式来实现机器人腿?

具有不同生命周期的对象的 Scala 蛋糕模式

scala - 蛋糕图案嵌套特征