Home > Back-end >  How can you access annotations on a field when generating LabelledGeneric?
How can you access annotations on a field when generating LabelledGeneric?

Time:12-27

Is there a way to tag a generated shapeless LabelledGeneric with information about annotations on fields?

For example

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

could we get something like

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

?

CodePudding user response:

You can have HLists FieldType['foo, Foo] :: FieldType['bar, Bar] :: HNil and Some[someAnnotation] :: None.type :: HNil using type classes shapeless.LabelledGeneric, shapeless.Annotations

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]]

Please notice that 'foo, 'bar (written as Witness.`'foo`.T, Witness.`'bar`.T for technical reasons) are singleton types that are subtypes of Symbol, not String.

If you really need an HList of intersections (with) or tuples (fieldName, annotation) then you can zip the HLists using one of type classes shapeless.ops.hlist.Zip, shapeless.ops.hlist.ZipOne, shapeless.ops.hlist.ZipWith.

  • Related