【发布时间】:2018-02-15 08:03:00
【问题描述】:
Scala 版本:2.12.4。
假设有一个空 trait 和一个带有函数的类,它接受 trait 实例作为隐式参数:
trait I
class A {
def fa()(implicit i: I): Unit = {}
}
让我们定义另一个类,它调用这个fa() 函数。我们将尝试从其伴生对象导入I 实例:
class B(a: A) {
import B._
def fb(): Unit = { a.fa() }
}
object B {
private implicit object II extends I
}
但是我们会遇到一个错误!
error: could not find implicit value for parameter i: I
def fb(): Unit = { a.fa() }
^
让我们在 B 类中创建隐式 val:
class B(a: A) {
import B._
private implicit val ii = II
def fb(): Unit = { a.fa() }
}
突然间,我们仍然面临一个错误:
error: ambiguous implicit values:
both value ii in class B of type => B.II.type
and object II in object B of type B.II.type
match expected type I
def fb(): Unit = { a.fa() }
^
- 编译器在第一种情况下看不到隐含,但在第二种情况下看到相同的隐含。为什么?
- 如何从伴生对象中导入这个隐式对象?
【问题讨论】: