我一直在玩这个小例子,试图更好地了解scala如何解决隐含问题。我刚刚发现了在伴随对象中声明隐式对象和隐式val之间的区别。
名为&#34的类型类;证据[-B]"在这个例子中是逆变的;例如证据[基数]可用于需要证据[派生]的地方。
我尝试使用Scala 2.11.7编译下面的代码:
model
但是,编译器会给出错误"含糊不清的隐含值":
model
根据我对隐式解析规则的理解,应首先搜索a.MyModelB_a.model.MyModelC_b
的伴随对象;然后是基类trait Evidence[-B] {
def hello(input: B): String
}
trait Base
object Base {
implicit object BaseEvidence extends Evidence[Base] {
override def hello(input: Base): String = "Evidence[Base] from implicit object"
}
}
class Derived extends Base
object Derived {
implicit val derivedEvidence: Evidence[Derived] = new Evidence[Derived] {
override def hello(input: Derived): String = "Evidence[Derived] from implicit val"
}
}
object Main extends App {
def hello[A](input: A)(implicit ev: Evidence[A]): Unit = {
println(ev.hello(input))
}
hello(new Derived)
}
的伴随对象。
当将隐式val derivedEvidence更改为隐式对象时,代码将编译:
Error:(24, 8) ambiguous implicit values:
both object BaseEvidence in object Base of type Base.BaseEvidence.type
and value derivedEvidence in object Derived of type => Evidence[Derived]
match expected type Evidence[Derived]
hello(new Derived)
^
这种行为的原因是什么?