我试图将一个案例类隐式转换为另一个案例类,但无法使代码生效。我的编辑给了我Seq [LegacyPhase]没有转换到预期的Seq [Phase]的错误。任何人都能指出我的方向吗?提前谢谢!
implicit def legacyToDashboardBrand(brand: LegacyDashboardBrand)(implicit session: Session): DashboardBrand = {
val phaseSeq: Seq[Phase] = (for { phaseDataset <- dashboardPhasesQ if phaseDataset.brandId === brand.id
} yield phaseDataset).list.toSeq
DashboardBrand(id = brand.id, projectId = brand.projectId, name = brand.name, currentPhase = brand.currentPhase, phases = phaseSeq)
}
implicit def legacyToDashboardPhase(phase: LegacyPhase): Phase = {
Phase(id = phase.id, brandId = phase.brandId, title = phase.title, steps = Seq())
}
编辑:如果我在第一个隐式转换定义中执行第二个隐式转换行,它就可以工作。
implicit def legacyToDashboardBrand(brand: LegacyDashboardBrand)(implicit session: Session): DashboardBrand = {
val legacyPhaseSeq = (for {
phaseDataset <- dashboardPhasesQ if phaseDataset.brandId === brand.id
} yield phaseDataset).list.toSeq
val phaseSeq: Seq[Phase] = legacyPhaseSeq.map(phase =>
Phase(id = phase.id, brandId = phase.brandId, title = phase.title, steps = Seq())
)
DashboardBrand(id = brand.id, projectId = brand.projectId, name = brand.name, currentPhase = brand.currentPhase, phases = phaseSeq)
}
答案 0 :(得分:1)
您的第二个解决方案(包含重复的代码)有效,因为您明确地将Seq[LegacyPhase]
转换为Seq[Phase]
。
您可以通过在legacyToDashboardBrand
转换函数的第一个LegacyPhase => Phase
函数中添加隐式参数来获得相同的结果:
implicit def legacyToDashboardBrand(
brand: LegacyDashboardBrand
)(implicit
session: Session,
phaseConv: LegacyPhase => Phase
): DashboardBrand = {
val phaseSeq: Seq[Phase] = (for {
phaseDataset <- dashboardPhasesQ if phaseDataset.brandId === brand.id
} yield phaseDataset).list.map(phaseConv).toSeq
DashboardBrand(
id = brand.id, projectId = brand.projectId, name = brand.name,
currentPhase = brand.currentPhase, phases = phaseSeq
)
}
这样,您的LegacyDashboardBrand => DashboardBrand
转换功能会使用您的LegacyPhase => Phase
转化功能。
注意:我不认为在隐式转换函数中查询数据库是个好主意。隐式转换本身就非常“神奇”,并且使您的代码更难以理解,添加查询数据库等副作用只会使其变得更加神奇。