【发布时间】:2012-09-28 10:55:24
【问题描述】:
在查找隐式时,Scala 编译器会在其他地方查找相关类的各个部分的伴生对象。但是,显然,如果在类本身中使用隐式转换,如果它是在伴随对象之前定义的,则它无法执行此查找。我能做的最小的例子是:
trait Counter[A] {
def count(a: A): Int
}
object Foo {
def foo[A](a: A)(implicit c: Counter[A]) = c.count(a)
}
case class Bar(id: Int) {
import Foo._
def count = foo(this)
}
object Bar {
implicit object BarCounter extends Counter[Bar] {
def count(b: Bar) = b.id
}
}
这无法编译说 could not find implicit value for parameter c: Counter[Bar] - 我使用的是 Scala 2.9.1。
有趣的事情(由 rjsvaljean 建议)是,如果我们颠倒顺序 - 也就是说,我们在 case class Bar 之前定义 object Bar - 一切都很好编译。
这是编译器错误吗?或者我遗漏了一些关于 Scala 范围规则的内容?
我还应该提到,这个问题只出现在隐式解决方案中。如果我们显式传递 BarCounter 对象,一切都可以正常编译。
【问题讨论】:
-
我不知道为什么,但是切换
object Foo和case class Foo的顺序使它不会抛出编译错误。 -
@rjsvaljean Weird - 有点像编译器故障。您介意将其添加为回复以便我接受吗?
-
我不知道。编辑包含该数据的问题并等待解释为什么它无法编译而不是如何修复它的答案不是更有用吗?甚至可能完全改变问题以使其更通用并重新发布。
标签: scala compiler-construction companion-object