我有以下案例类
case class Test(field1: Int, field2: String)
我希望能够有一个方法,对于列名,它可以将该值映射到其他,我希望它是类型安全,这意味着功能f应该接受与符号K相同的类型
def mapColumn[A, K, KV, Repr <: HList, Out](obj: A, witness: Witness.Aux[K], f: KV => Out)
(implicit mkLens: MkFieldLens[A, K],
gen: LabelledGeneric.Aux[A, Repr]): Out = ???
如何使KV成为符号K的类型?
例如
mapColumn(Test(1, "hello"), 'field1, (v: Int) => v + 1) // this should retrieve 2
mapColumn(Test(1, "hello"), 'field2, (v:String) => v + 1) // this should retrieve "hello1"
mapColumn(Test(1, "hello"), 'field2, (v: Int) => v + 1) // this should be a compilation error
答案 0 :(得分:1)
我找到了方法
def mapColumn[A, K, KV, Repr <: HList, Out](obj: A, witness: Witness.Aux[K], f: KV => Out)
(implicit mkLens: MkFieldLens[A, K],
gen: LabelledGeneric.Aux[A, Repr],
fieldTypesRest: Selector.Aux[Repr, K, KV]): Out = ???