Diverging implicit expansion for type class

梦想与她 提交于 2020-01-13 13:13:53

问题


I'm trying to extend the Parser type class from this blog post to support nested case classes parsing. Since I'm new to shapeless, I've decided to start with the non-general case, that would only support a case class with 2 fields that are themselves case classes. To illustrate this better, here's the case classes definition first:

case class Person(name: String, age: Int)
case class Family(husband: Person, wife: Person)

In addition to the code from that blog post, I've created one more implicit function that is supposed to support my case, parsing Family class from the string like "Hans,70|Emmy,60" by dividing the string in 2 parts by '|', then parsing those 2 separate parts independently, and at last combining the result. Here how it looks like:

implicit def nestedCaseClassParser[A, B, C]
  (
    implicit pb: Parser[B],
    pc: Parser[C],
    gen: Generic.Aux[A, B :: C :: HNil]
  ): Parser[A] = new Parser[A] {
    override def apply(s: String): Option[A] = {
      val tmp = s.span(_ != '|') match {
        case (h, t) =>
          for {
            a <- pb(h)
            b <- pc(t.substring(1))
          } yield a :: b :: HNil
      }
      tmp.map(gen.from)
    }
  }

Then, when I'm trying to parse it like this:

val p = Parser.apply[Family]("hello,1|hello,1")

I'm getting the following compilation error:

<console>:83: error: diverging implicit expansion for type Parser[Family]
starting with method nestedCaseClassParser in object Parser
       val p = Parser.apply[Family]("hello,1|hello,1")
                             ^

I'm not asking for a full solution for the problem of fully generic nested case class parsing, as I'm eager to find it myself, but I'd really appreciate an explanation of what's going wrong with this code, and how can I make it work on this simple level.

EDIT: Since I've been able to overcome the initial problem, I've created a separate questions for the thing I've run into next.

来源:https://stackoverflow.com/questions/33787931/diverging-implicit-expansion-for-type-class

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