how to use shapeless to detect field type annotation

谁说我不能喝 提交于 2019-12-05 12:58:27

Looking at the macro of Annotation, it rejects type that is not a product or coproduct straight up

val annTreeOpts =
  if (isProduct(tpe)) { ... }
  else if (isCoproduct(tpe)) { ... }
  else abort(s"$tpe is not case class like or the root of a sealed family of types")

this is quite unfortunate, as collecting type annotations at per field symbol level could be quite useful sometimes.

There is another type class Annotations defined in the same file that can actually collect particular annotations on field into an HList. However problem is the field information is totally lost. There is a clumsy way to hack things together to serve my use case...

// A is our annotation
// B is our result type    
// C is our case class with some fields annotated with A

def empty: B = ???
def concat(b1: B, b2: B): B = ???
def func(a: A, nm: String): B = ???

object Collector extends Poly2 {
   implicit def some[K <: Symbol](implicit witness: Witness.Aux[K]) = 
     at[B, (K, Some[A])] { case (b, (_, a)) => concat(b, func(a.get, witness.value.name)) }
   implicit def none[K <: Symbol] = at[B, (K, None.type)] { case (b, _) => b }
}

def collect[HL <: HList, RL <: HList, KL <: HList, ZL <: HList](implicit 
    iso: LabelledGeneric.Aux[C, HL]
  , annot: Annotations.Aux[A, C, RL]
  , keys: Keys.Aux[HL, KL]
  , zip: Zip.Aux[KL :: RL :: HNil, ZL]
  , leftFolder: LeftFolder.Aux[ZL, B, Collector.type, B]): B = {
  zip(keys() :: annot() :: HNil).foldLeft(empty)(Collector)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!