根据Scala Spec(2.8),对于要发现的隐式,它必须在本地范围,继承范围或 companion 对象中定义 . 鉴于此,在我看来,下面的代码应该没有明确导入伴随对象的内容 . 我在Scala库源中看到了这个(例如CanBuildFrom) . 似乎我应该能够从XX类的定义之外调用XX.foo()并使用我所使用的伴随类中的隐式参数 . 我错过了什么?
object XX {
implicit def XYZ[T]: (T) => Unit = null
}
class XX {
// import XX._ // Works with this line uncommented...
def foo(s: String)(implicit f: (String) => Unit): Unit = {
if (f == null)
println("Just: " + s)
else
f(s)
}
def bar {
foo("abc"){ s => println("Func: " + s)}
foo("xyz") // <-- Compile error here: could not find implicit value for parameter f
}
}
1 回答
我总是将规范解释为隐含可以在隐式参数的伴随对象中定义,而不是包含定义的类 . 像这样的东西:
在规范的第7.2节中似乎很清楚:
你可以引用指示定义的包含类的伴随对象的部分吗?