【问题标题】:How can you access annotations on a field when generating LabelledGeneric?生成 LabelledGeneric 时如何访问字段上的注释?
【发布时间】:2022-01-21 06:13:05
【问题描述】:

有没有办法用关于字段注释的信息标记生成的无形LabelledGeneric

例如

case class Example(@someAnnotation foo: Foo, bar: Bar)

我们可以得到类似的东西

FieldType["foo" with Annotations(someAnnotation :: HNil), Foo] :: FieldType["bar", Bar] :: HNil

?

【问题讨论】:

    标签: scala shapeless


    【解决方案1】:

    您可以使用类型类 shapeless.LabelledGenericshapeless.Annotations 拥有 HLists FieldType['foo, Foo] :: FieldType['bar, Bar] :: HNilSome[someAnnotation] :: None.type :: HNil

    implicitly[LabelledGeneric.Aux[Example,
      FieldType[Witness.`'foo`.T, Foo] :: FieldType[Witness.`'bar`.T, Bar] :: HNil]]
    
    implicitly[Annotations.Aux[someAnnotation, Example,
      Some[someAnnotation] :: None.type :: HNil]]
    

    请注意'foo'bar(出于技术原因写成Witness.`'foo`.TWitness.`'bar`.T)是Symbol 的子类型,而不是String

    如果您确实需要交叉点的 HList (with) 或元组 (fieldName, annotation),那么您可以使用类型类 shapeless.ops.hlist.Zipshapeless.ops.hlist.ZipOneshapeless.ops.hlist.ZipWith 之一来压缩 HList。

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      相关资源
      最近更新 更多