假设我想遍历这里描述的案例类泛型表示
我已经定义了一些类型类来描述字段:
trait Described[X] extends (X => String)
object Described{
def apply[X](x: X)(implicit desc: Described[X]) = desc(x)
}
定义了一些实例:
implicit object DoubleDescribed extends Described[Double]{
def apply(x: Double) = x.formatted("%01.3f")
}
和普通用户:
import shapeless._
import shapeless.labelled.FieldType
import shapeless.ops.hlist.LeftFolder
object DescrFolder extends Poly2{
implicit def field[X, S <: Symbol](implicit desc: Described[X],
witness: Witness.Aux[S]):
Case.Aux[Seq[String], FieldType[S, X], Seq[String]] =
at[Seq[String], FieldType[S, X]](
(descrs, value) => descrs :+ f"${witness.value.name}: ${desc(value)}")
}
def describe[T <: Product, Repr <: HList](struct: T)
(implicit lgen: LabelledGeneric.Aux[T,Repr],
folder: LeftFolder.Aux[Repr, Seq[String], DescrFolder.type, Seq[String]]
): String = {
val repr = lgen.to(struct)
val descrs = folder(repr,Vector())
descrs.mkString(struct.productPrefix + "{", ",", "}")
}
所以现在我可以写了
case class Point(x: Double, y: Double, z: Double)
describe(Point(1,2,3.0))
并得到
res1: 字符串 = 点{x: 1,000,y: 2,000,z: 3,000}
现在我想使用shapeless
标签定义一些字段元数据:
import tag._
trait Invisible
val invisible = tag[Invisible]
implicit def invisibleDescribed[X](implicit desc: Described[X])
: Described[X @@ Invisible] =
new Described[X @@ Invisible]{
def apply(x: X @@ Invisible) = desc(x: X) + "[invisible]"
}
所以Described(invisible(0.5))
现在成功生产
res2: String = 0,500[不可见]
但随着重新定义
case class Point(x: Double, y: Double, z: Double @@ Invisible)
describe(Point(1,2,invisible(3.0)))
产生编译错误:
LeftFolder.Aux[this.Out,Seq[String],DescrFolder.type,Seq[String]]
错误:以类中的方法开头的类型的发散隐式扩展invisibleDescribed
...
我认为该类型X with Tag[Y] with KeyTag[K,X]
没有被识别为FieldType[S, X]
但无法猜测如何修复它。
如何定义适合LeftFolder
这种情况?