假设我想遍历here所述的案例类通用表示形式
我定义了一些类型类来描述字段:
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))
并得到
现在,我想使用
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))
现在可以成功产生但随着重新定义
case class Point(x: Double, y: Double, z: Double @@ Invisible)
describe(Point(1,2,invisible(3.0)))
产生编译错误:
我认为
X with Tag[Y] with KeyTag[K,X]
类型不能识别为FieldType[S, X]
,但无法猜测如何解决。如何为这种情况定义适当的
LeftFolder
? 最佳答案
您的问题根本不涉及shapeless
。实际上可以简化为:
trait Described[T]
trait Invisible
implicit val doubleDescribed: Described[Double] = ???
implicit def invisibleDescribed[T](
implicit desc: Described[T]
): Described[T with Invisible] = ???
implicitly[Described[Double with Invisible]]
Double @@ Invisible
可以“表示为” Double with Invisible
。请注意Double with Invisible <: Double
。当编译器尝试获取隐式
Described[Double with Invisible]
时,它会正确地提示发散的隐式扩展:doubleDescribed
和invisibleDescribed
。回到原始代码,一个简单的解决方法是将
invisibleDescribed
重写为:implicit def invisibleDescribed[X, I <: X @@ Invisible](
implicit desc: Described[X]
): Described[I] = new Described[I]{
def apply(x: I) = desc(x: X) + "[invisible]"
}
关于scala - 在LabelledGenerics中使用无形标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32250845/