4

Here is my test code :

object ImplicitTest {
  import JoesPrefs._
  Greeter.greet("Joe") // could not find implicit value for parameter prompt: 
}
class PreferredPrompt(val preference: String)

object JoesPrefs {
  implicit val prompt = new PreferredPrompt("Yes, master> ")
}
object Greeter {
  def greet(name: String)(implicit prompt: PreferredPrompt) = {
    println("Welcome, " + name + ". The system is ready.")
    println(prompt.preference)
  }
}

I use scala 2.11.12, don't know why this implicit not work until add type annotation to val :

object JoesPrefs {
  implicit val prompt: PreferredPrompt  = new PreferredPrompt("Yes, master> ")
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
yuxh
  • 924
  • 1
  • 9
  • 23

1 Answers1

4

So, the exact internal are a bit wild, but basically it boils down to the compilation order of the code. When you add the type annotation, the val is "compiled and put in scope" sooner than when you do not, and it becomes available to resolve in ImplicitTest.

Funnily (at least for me ^^), you can also move ImplicitTest to be on a line of code after the JoesPref object (or move it to its own file), it will compile without the type annotation.

C4stor
  • 8,355
  • 6
  • 29
  • 47
  • yes, it act like you told. Do you know anywhere mentioning about this situation? – yuxh Jul 20 '20 at 08:49
  • There's this comment by the language creator : https://github.com/scala/bug/issues/801#issuecomment-292352399 – C4stor Jul 20 '20 at 08:55