Scala 隐式参数,其默认值在伴生对象中定义
根据 Scala 规范 (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
}
}
According to the Scala Spec (2.8), for an implicit to be found it must be defined in local scope, inherited scope, or in a companion object. Given that, it seems to me that the following code should work without an explicit import of the contents of the companion object. I see this used in the Scala library source (eg. CanBuildFrom). It also seems that I should be able to call XX.foo() from outside the definition of the XX class and have my implicit parameter from the companion class used. What am I missing?
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我总是将规范解释为隐式参数可以在隐式参数的伴随对象中定义,而不是在包含定义的类中定义。像这样的事情:
规范第 7.2 节似乎很清楚:
您能引用指示定义的包含类的伴生对象的部分吗?
I always interpreted the spec to mean that the implicit can be defined in the companion object of the implicit parameter, not the class containing the definition. Something like this:
It seems clear in Section 7.2 of the spec:
Can you quote the part that indicates the companion object of the containing class of the definition?