scalacompanion-object

Order of definition matters in Scala?


When looking for implicits, the Scala compiler looks, among other places, in the companion object of the various parts of the classes involved. Apparently, though, it fails to perform this lookup when the implicit conversion is used in the class itself, if it is defined before the companion object. The minimal example I was able to cook up is:

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
  }
}

This fails to compile saying could not find implicit value for parameter c: Counter[Bar] - I am using Scala 2.9.1.

The interesting thing (suggested by rjsvaljean) is that if we invert the order - that is, we define object Bar before case class Bar - verything compiles fine.

Is this a compiler bug? Or I am missing something about the scope rules of Scala?

I should also mention that this problem only arises with implicit resolution. If we explicitly pass the BarCounter object, everything compiles fine.


Solution

  • It seems to be an actual compiler bug. I have posted it here.