2015-09-14 97 views
0

我想隱式轉換一個案例類到另一個案例類,但不能讓代碼工作。我的編輯給了我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

你能告訴我們確切的錯誤嗎?什麼是'dashboardPhasesQ'? –

+0

嘿,彼得。 dashboardPhasesQ是一個表查詢。 val dashboardPhasesQ = TableQuery [LegacyPhaseTable] –

回答

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轉換功能。

注意:我不認爲在隱式轉換函數中查詢數據庫不是一個好主意。隱式轉換本身非常「神奇」,並且使代碼更難理解,添加諸如查詢數據庫的副作用只會使其更加神奇。

+0

感謝Peter的嘗試,但是它的結果與以前一樣...它不會將它轉換爲靜態。 –

+0

我們可以使用隱式傳遞的'phaseConv'來映射'LegacyPhases',參見更新。 –

+0

謝謝,彼得,現在工作。任何想法爲什麼它不會在第一種情況下工作?並相信我,我明白你來自暗示 –