This is continuation of Diverging implicit expansion for type class. I've came up with another version that still doesn't compile, but now for another reason, hence a different question. Here's what I did:
I've basically added a new typeclass NestedParser
for the cases where some case class consists of other case classes.
trait Parser[A] {
def apply(s: String): Option[A]
}
trait NestedParser[A] {
def apply(s: String): Option[A]
}
object Parser {
def apply[A](s: String)(implicit parser: Parser[A]): Option[A] = parser(s)
}
object NestedParser {
def apply[A](s: String)(implicit parser: NestedParser[A]): Option[A] = parser(s)
}
I've changed the previous implicit function to return the NestedParser
to avoid diverging implicit expansions. Otherwise it's same as before:
implicit def nestedCaseClassParser[A, B, C]
(
implicit pb: Parser[B],
pc: Parser[C],
gen: Generic.Aux[A, B :: C :: HNil]
): NestedParser[A] = new NestedParser[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)
}
}
Case classes are same as before:
case class Person(name: String, age: Int)
case class Family(husband: Person, wife: Person)
Now when I try to parse the Family
, I get the following compile error:
scala> NestedParser[Family]("")
<console>:32: error: could not find implicit value for parameter parser: NestedParser[Family]
NestedParser[Family]("")
However, it doesn't make sense to me. The function above clearly provides the implicit instance of NestedParser
. Why doesn't it satisfy the compiler?