鉴于这些ADT:
case class SourceRecord(name: String, number: Int)
case class TargetRecord(number: Int, name: String)
我可以轻松地从SourceRecord
映射到TargetRecord
:
val sourceGen = LabelledGeneric[SourceRecord]
val targetGen = LabelledGeneric[TargetRecord]
val sourceRecord = SourceRecord("record_1", 1)
val targetRecord = targetGen.from(sourceGen.to(sourceRecord).align[targetGen.Repr])
但是,如果我引入新类型,我很难理解如何执行转换:
case class MyNumber(value: Int) extends AnyVal
case class SourceRecord(name: String, number: Int)
case class TargetRecord(number: MyNumber, name: String)
Error: could not find implicit value for parameter align: shapeless.ops.hlist.Align[sourceGen.Repr,targetGen.Repr]
我猜我需要以某种方式提供一个类型类来将Int
与MyNumber
对齐,但我不知道如何。有谁能告诉我?
答案 0 :(得分:0)
手动,您可以按如下方式定义:
import shapeless.labelled.FieldType
import shapeless.ops.hlist.Align
import shapeless.record.Record
import shapeless.{::, HNil, Witness}
import shapeless.syntax.singleton._
implicit val align: Align[Record.`'name -> String, 'number -> Int`.T, Record.`'number -> MyNumber, 'name -> String`.T] = {
case s :: (i: FieldType[Witness.`'number`.T, Int]) :: HNil => 'number ->> MyNumber(i) :: 'name ->> s :: HNil
}