找不到类型类的隐式方法 [英] Implicit method for typeclass not found
问题描述
这是为类型类发散隐式扩展的延续.我想出了另一个仍然无法编译的版本,但现在出于另一个原因,因此是一个不同的问题.这是我所做的:
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:
我基本上添加了一个新的类型类 NestedParser
,用于某些 case 类包含其他 case 类的情况.
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)
}
我已将之前的隐式函数更改为返回 NestedParser
以避免发散隐式扩展.否则和以前一样:
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 class Person(name: String, age: Int)
case class Family(husband: Person, wife: Person)
现在,当我尝试解析 Family
时,出现以下编译错误:
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]("")
然而,这对我来说没有意义.上面的函数清楚地提供了 NestedParser
的隐式实例.为什么它不满足编译器?
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?
推荐答案
嗯,据我所知,你没有提供任何 nestedCaseClassParser
需要的隐式 Parser
实例.
Well, as far as I can see you are not providing any implicit Parser
instances which nestedCaseClassParser
requires.
这篇关于找不到类型类的隐式方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!