Scala case类中通过shapeless递归打印字段名
我有下一个代码:Scala case类中通过shapeless递归打印字段名,scala,shapeless,Scala,Shapeless,我有下一个代码: trait X case class Bar(id: Int) extends X case class Foo(id: Int, bar: Bar) extends X 我想用内部类打印Foo的所有字段,我使用shapeless,并创建多边形: object print1 extends Poly1 { implicit def c[K, V]( implicit wk: Witness.Aux[K]) = { at[FieldType[K, V]]
trait X
case class Bar(id: Int) extends X
case class Foo(id: Int, bar: Bar) extends X
我想用内部类打印Foo
的所有字段,我使用shapeless,并创建多边形:
object print1 extends Poly1 {
implicit def c[K, V](
implicit wk: Witness.Aux[K]) = {
at[FieldType[K, V]](field => {
wk.value
})
}
}
val foo = Foo(1, Bar(10))
val fooLgen = LabeledGeneric[Foo]
pritnln(fooLgen.to(foo).map(print1)) // => 'id::'bar
但是如何打印内部类呢 在您的示例中,创建键的
HList
,然后打印它。您可以按如下方式递归执行此操作:
trait LowerPriorityPrint1 extends Poly1 {
implicit def c[K, V](implicit wk: Witness.Aux[K]) = {
at[FieldType[K, V]](field => {
wk.value
})
}
}
object print1 extends LowerPriorityPrint1 {
implicit def csub[K, V, L <: HList](
implicit l : LabelledGeneric.Aux[V, L],
mapper : Mapper[print1.type, L]
) = {
at[FieldType[K, V]](field => {
l.to(field).map(print1)
})
}
}
val foo = Foo(1, Bar(10))
val fooLgen = LabelledGeneric[Foo]
println(fooLgen.to(foo).map(print1)) // => 'idFoo :: 'idBar :: HNil :: HNil
trait LowerPriorityPrint1扩展了Poly1{
隐式定义c[K,V](隐式工作:Witness.Aux[K])={
在[FieldType[K,V]](字段=>{
工作价值
})
}
}
对象print1扩展了LowerPriorityPrint1{
隐式def csub[K,V,L{
l、 至(字段).map(打印1)
})
}
}
瓦尔富奥=富奥(1,巴(10))
val-Duwgen=标签式电子元件[Foo]
println(douggen.to(foo.map(print1))/=>'idFoo::'idBar::HNil::HNil
无形状在编译时工作,因此您必须使用隐式在类型级别创建递归。
c
和cSub
对于同一个键同时存在,您可以通过在supertrait中声明优先级较低的一个来决定首先解决哪一个无形状如何理解应该使用哪个方法为什么不可能将LabeledGeneric与原始c
方法一起使用?shapeless在编译时工作,因此您必须使用隐式在类型级别创建递归。c
和cSub
对于同一个键同时存在,您可以通过在supertr中声明优先级较低的键来决定首先解决哪一个寻找scala隐式解析规则