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> ")
}
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.