Deriving decoder instances of case classes with a single field

青春壹個敷衍的年華 提交于 2019-12-06 16:49:30

I did use =:= instead of <:< however swapped the sides of R and H::HNil and that seemed to work:

case class CellDecoder[A](decode: String => A)

implicit val stringCellDecoder: CellDecoder[String] = CellDecoder(identity)

implicit def caseClassCellDecoder[A, R, H](implicit
                                           gen: Generic.Aux[A, R],
                                           ev: (H :: HNil) =:= R,
                                           d: CellDecoder[H]
                                            ): CellDecoder[A] = CellDecoder(
  (str: String) => gen.from(ev(d.decode(str)::HNil))
)

So I was able to use it as follows:

case class TestDecoder(test: String)

def doDecode[A: CellDecoder](str: String): A = {
  implicitly[CellDecoder[A]].decode(str)
}

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