Compiler cannot find right implicits for shapeless LabelledGeneric

蓝咒 提交于 2019-12-05 22:14:51

You'll need to prove that the record that represents A has a ToMapRec instance, which you can do like this:

def convert[A, R <: HList](cc: A)(implicit
  gen: LabelledGeneric.Aux[A, R],
  tmr: ToMapRec[R]
) = tmr(gen.to(cc))

You can also introduce a new type class to clean this up a bit:

trait CcToMapRec[A] { def apply(a: A): Map[String, Any] }

object CcToMapRec {
  implicit def ccToMapRec[A, R <: HList](implicit
    gen: LabelledGeneric.Aux[A, R],
    tmr: ToMapRec[R]
  ): CcToMapRec[A] = new CcToMapRec[A] {
    def apply(a: A): Map[String, Any] = tmr(gen.to(a))
  }
}

And then your method just needs a single implicit parameter:

def convert[A](cc: A)(implicit ctmr: CcToMapRec[A]) = ctmr(cc)

But you'll still need to thread this instance through any method with a generic type that you intend to convert.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!