假設我想穿越案例類通用表示所描述here使用無形的標籤與LabelledGenerics
我定義了一些類型類描述字段:
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: String = Point{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[invisible]
但隨着重新定義
case class Point(x: Double, y: Double, z: Double @@ Invisible)
describe(Point(1,2,invisible(3.0)))
產生編譯錯誤:
Error: diverging implicit expansion for type
LeftFolder.Aux[this.Out,Seq[String],DescrFolder.type,Seq[String]]
starting with methodinvisibleDescribed
in class ...
我相信這種類型的X with Tag[Y] with KeyTag[K,X]
不識別爲FieldType[S, X]
,但不能猜測如何解決它。
如何定義合適的LeftFolder
這種情況?