Scala implicit parameter scope
I've spent all morning looking at Scala's indirect uses, including a very excellent answer here: Where does Scala look for implicits?
But alas, I am still confused. Let me give you an example of what I am 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, they tell me could not find implicit value for parameter w: Widget
. Now, weirdly, if I move the class Widget
and object, and also the class Example
inside the object implicit_test
, then it works.
Please explain to me if you like how exactly Scala identifies which implicit val to use!
source to share
Your code should work and it works for me.
Did you accidentally choose the type in the REPL? If so, there is something special about companion objects. In scala, a companion object must be in the same file as its class (otherwise the code is valid, but it is not a "companion object", just an object with the same name, not part of the implicit scope). There are no files in the REPL, but the class and its companion must be defined at the same time. To do this, you must enter them in insert mode.
Type :paste
, then paste (or just type) at least both the object widget and the class widget (you can paste the rest into the code at the same time, but this is optional) and then CTRL-D
. This should work.
source to share