Saurav Shah
Saurav Shah

Reputation: 681

Scala implicit logic for companion objects

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?

Upvotes: 1

Views: 230

Answers (1)

Ravi Kiran
Ravi Kiran

Reputation: 1139

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.

Upvotes: 5

Related Questions