I've spent all morning reading up on how Scala scopes implicits, including the very excellent answer here: Where does Scala look for implicits?
But alas, I am still confused. Let me give an example of what I'm trying to do:
object Widget {
implicit val xyz: Widget = new Widget("xyz")
}
class Widget(val name: String) {
override def toString = name
}
class Example {
def foo(s: String)(implicit w: Widget): Unit = {
println(s"Got $s with $w")
}
def bar {
foo("abc") // Compiler error at this line
}
}
object implicit_test {
val x = new Example()
x.bar
}
So, I expect to see something like Got abc with xyz
. Instead I get told could not find implicit value for parameter w: Widget
. Now, strangely if I move the Widget
class and object as well as the Example
class inside the implicit_test
object, then this works.
Please explain to me again, if you will, how exactly Scala identifies which implicit val to use!