【发布时间】:2016-01-20 06:10:27
【问题描述】:
我有一些具有相同自类型的 scala 特征,声明如下。
trait BookDbModule {
self: DbConfig => // Abstract this to a parent trait
/* ... */
}
trait AuthorDbModule {
self: DbConfig => // Abstract this to a parent trait
/* ... */
}
我正在尝试将 self-type 声明抽象为一个父 trait,这样这些特征中的每一个都不必定义 self-type。我尝试了以下方法。
trait DbModule {
self: DbConfig =>
// Some common DbModule methods
}
// !!! Illegal Inheritance, self-type BookDbModule does not conform to DbConfig
trait BookDbModule extends DbModule {
// What needs to be used instead of extends?
/* ... */
}
// !!! Illegal Inheritance, self-type AuthorDbModule does not conform to DbConfig
trait AuthorDbModule extends DbModule {
// What needs to be used instead of extends?
/* ... */
}
错误消息Illegal Inheritance 对我来说很有意义,因为BookDbModule 没有扩展DbConfig。
在 Scala 中有什么方法可以在父 trait 中强制实现子特征的自我类型?
更新: 这个问题似乎有点令人困惑。
我想要实现的是,我想省略为 BookDbModule 和 AuthorDbModule 设置自我类型的必要性,方法是扩展(或任何其他 scala 功能)父特征 DbModule 同时具有自我类型987654329@.
所以,基本上,我正在寻找一种方法,通过在父 DbModule 中声明 self-type 而不是在那些带有 DbConfig 的类中扩展子特征(BookDbModule 和 AuthorDbModule)儿童特质。
// This works but is there any way to omit necessity to write
// self: DbConfig =>
trait AuthorDbModule extends DbModule {
self: DbConfig =>
/* ... */
}
如果仍然令人困惑,请告诉我。
谢谢!
【问题讨论】:
-
请说明您要达到的目标。这些消息(至少对我而言)确实说它们“强制执行自我类型的特征”。
-
嗨@RobStarling,我已经更新了我的问题。请看一下。谢谢!
-
感谢更新,更清楚了
-
啊!知道了。抱歉,但我认为答案是“不”。
标签: scala inheritance traits self-type