1
object Test extends App {

  def print(s: String)(implicit p: Prefixer) = {
    println(p.prefix + s)
  }

  print("test")

}

case class Prefixer(prefix: String)

object Prefixer {
  implicit val p = Prefixer("***")
}

The above code does not compile, because the compiler is not able to find an implicit value for Prefixer. However, if I put the case class Prefixer and the companion object in another file it works. Why is that?

Saurav Shah
  • 621
  • 3
  • 8
  • 13
  • Duplicate of http://stackoverflow.com/questions/25468583/why-cant-scala-find-my-typeclass-instance-defined-implicitly-in-the-companion-o – som-snytt Aug 31 '14 at 11:46

1 Answers1

5

It is to do with the order of declaration. It also works if you just move the Prefixer and its companion above the main object. When the class is in another file, the compiler can scan that file first & then come to the file implementing the App.

Ravi Kiran
  • 1,099
  • 6
  • 10