根据 Scala Spec (2.8),要找到隐式,它必须在本地范围、继承范围或伴随对象中定义。鉴于此,在我看来,以下代码应该在没有显式导入伴随对象内容的情况下工作。我在 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
}
}