【发布时间】:2017-05-06 14:07:21
【问题描述】:
我写了这段代码
trait Pet
case class Dog() extends Pet
case class Cat() extends Pet
def foo(i: Int)(implicit d: Dog) = println("dog")
def foo(i: Int)(implicit c: Cat) = println("cat")
def doFoo(a: Pet) = {
a match {
case a: Dog => implicit val dog : Dog = a; foo(10)
case a: Cat => implicit val cat : Cat = a; foo(10)
case _ => println("unknown")
}
}
我收到一个错误
cmd0.sc:8: ambiguous reference to overloaded definition,
both method foo in object cmd0 of type (i: Int)(implicit c: $sess.cmd0.Cat)Unit
and method foo in object cmd0 of type (i: Int)(implicit d: $sess.cmd0.Dog)Unit
match argument types (Int)
case a: Dog => implicit val dog : Dog = a; foo(10)
^
cmd0.sc:9: ambiguous reference to overloaded definition,
both method foo in object cmd0 of type (i: Int)(implicit c: $sess.cmd0.Cat)Unit
and method foo in object cmd0 of type (i: Int)(implicit d: $sess.cmd0.Dog)Unit
match argument types (Int)
case a: Cat => implicit val cat : Cat = a; foo(10)
但是为什么感觉有歧义...因为在我的第一种情况下匹配有一个隐含的 val dog,而在我的第二种情况下匹配有一个隐含的 val cat。所以它应该找到正确的隐式。
为什么不能正确解析?
我的环境是
Welcome to the Ammonite Repl 0.8.2
(Scala 2.12.1 Java 1.8.0_121)
^
【问题讨论】:
标签: scala