【问题标题】:Shapeless generic ZipWith with static poly具有静态多边形的无形通用 ZipWith
【发布时间】:2022-01-26 19:24:12
【问题描述】:

我有一些代码:

case class Name(name: String) extends StaticAnnotation

case class Example(@Name("baz") foo: String, bar: Int)

object nameAnnotationZip2 extends Poly2 {
  implicit val newName: Case.Aux[Symbol, Some[Name], String] =
    at((_, name) => name.value.name)

  implicit val existingName: Case.Aux[Symbol, None.type, String] =
    at((field, _) => field.name)
}

def renameRecord[
    A,
    Record <: HList,
    Fields <: HList,
    Annotations <: HList,
    ZippedWith <: HList
](a: A)(implicit
    generic: LabelledGeneric.Aux[A, Record],
    fields: Keys.Aux[Record, Fields],
    annotations: Annotations.Aux[Name, A, Annotations],
    zippedWith: ZipWith.Aux[
      Fields,
      Annotations,
      nameAnnotationZip2.type,
      ZippedWith
    ]
) = {
  val record = generic.to(a)
  println(fields())
  println(annotations())
  zippedWith(fields(), annotations())
}

renameRecord(Example("qix", 5))

它尝试从具有基于注释的重命名键的实例创建记录。不幸的是,它总是给我一个

找不到参数 zippedWith 的隐式值:shapeless.ops.hlist.ZipWith.Aux[Fields,Annotations,nameAnnotationZip2.type,ZippedWith]

我还没有添加ZipWithKeys 位,但我相信我需要先解决这个问题。

我相信我只是在某种程度上完全错误地使用了Poly,但是编译器消息并没有帮助我找到我的错误。

编辑/第二部分: 我可以使用Zip 而不是ZipWith,转换为Sized,简单地映射没有Poly 的seq,然后转换回HList。这样做和上面的运行时性能有什么区别?

【问题讨论】:

    标签: scala generics shapeless


    【解决方案1】:

    Fields 的类型不是Symbol,而是Symbol @@ "foo"Case 的泛型参数不是变体,因此 nameAnnotationZip2 没有为 Fields 的元素定义。

    向案例添加通用参数可以解决问题

    object nameAnnotationZip2 extends Poly2 {
      implicit def newName[K <: Symbol]: Case.Aux[K, Some[Name], String] =
        at((_, name) => name.value.name)
    
      implicit def existingName[K <: Symbol]: Case.Aux[K, None.type, String] =
        at((field, _) => field.name)
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      相关资源
      最近更新 更多