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.