8

假设我想遍历这里描述的案例类泛型表示

我已经定义了一些类型类来描述字段:

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这种情况?

4

1 回答 1

0

你的问题根本不涉及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]时,它会正确地抱怨发散的隐式扩展:doubleDescribedinvisibleDescribed.

回到您的原始代码,一个简单的解决方法可能是重写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]"
}
于 2017-04-04T07:31:18.773 回答