[英]Scala Override Generic Method from a Trait
我有一个这样的特征定义:
trait MyTrait {
def dbService[M[_]]: DBService[M[_]]
def appConfig: AppConfig
def supervisorActor: ActorRef
}
我有一个如下特征的实现:
object MyTrait {
def apply(system: ActorSystem, actorMaterializer: Materializer): MyTrait = new MyTrait {
override val appConfig: AppConfig = AppConfig.load()
// Get the ERROR here saying Value dbService overrides nothing
override val dbService: DBService[Task] = DBServiceT.asTask(appConfig.dbConfig)(scala.concurrent.ExecutionContext.Implicits.global)
override val supervisorActor: ActorRef =
system.actorOf(
SupervisorActor.props(appConfig)(monix.execution.Scheduler.Implicits.global),
s"${appConfig.appName}-supervisor"
)
}
}
我的DBService特性如下所示:
trait DBService[M[_]] {
def allPowerPlants(fetchOnlyActive: Boolean): M[Seq[PowerPlantRow]]
def powerPlantsPaginated(filter: PowerPlantFilter): M[Seq[PowerPlantRow]]
def allPowerPlantsPaginated(fetchOnlyActive: Boolean, pageNumber: Int): M[Seq[PowerPlantRow]]
def powerPlantById(id: Int): M[Option[PowerPlantRow]]
def newPowerPlant(powerPlantRow: PowerPlantRow): M[Int]
}
然后,我有一个类似于以下的实现:
class DBServiceTask private (dbConfig: DBConfig)(implicit ec: ExecutionContext) extends DBService[Task] { self =>
....
....
}
尝试此操作时,我的MyTrait对象出现错误,提示:
Value dbService overrides nothing
有什么想法我做错了吗?
此签名:
def dbService[M[_]]: DBService[M[_]]
描述了可以为ANY类型构造函数M[_]
创建DBService的内容。 要对其进行类型检查,它必须能够创建所有以下内容:
DBService[Task]
DBService[Future]
DBService[Array]
DBService[Option]
DBService[Ordering]
由于您的实现只能产生单个 M[_]
(在您的情况下为Task
),因此您不能具有该签名。
您的选择包括将类型参数作为类型参数移动到特征定义:
trait MyTrait[M[_]] {
def dbService: DBService[M] // also note that [_] part should not be here
}
或类型成员:
trait MyTrait {
type M[_]
def dbService: DBService[M]
}
但是,后者可能会给您带来麻烦
编辑 :当然,您也可以选择直接指定Task
:
trait MyTrait {
def dbService: DBService[Task]
}
val dbService: DBService[Task]
是类型DBService[Task]
的值,而您需要定义一个将类型作为“参数”的函数: def dbService[M[_]]: DBService[M[_]]
我认为您希望自己的特征看起来像这样:
trait MyTrait[M[_]] {
def dbService: DBService[M[_]]
def appConfig: AppConfig
def supervisorActor: ActorRef
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.