Consider this case class:
case class IntPrinter(implicit val i: Int) {
def print()(implicit i: Int) = println(i)
}
I can instance it explicitly passing a value for the implicit argument like this:
val p = IntPrinter()(9)
I’ve been told in IRC that, from now on, the explicitly passed value will be implicitly passed to print when being called, but that’s not the case:
p.print()
error: could not find implicit value for parameter i: Int
Am I doing something wrong or I’ve misunderstood/been given incorrect information? Is there any way to achieve this?
EDIT: as a matter of fact it works as expected if I import p._ like this:
import p._
p.print()
Which indeed prints 9.
Is this the correct behaviour? Is using import as bad idea as it sounds? How do I workaround this?
Indeed it’s the correct behaviour.
implicitvalues are only searched in current scope and callingprintoutsideIntPrintermeans it’s not on the class scope (obviously) and the reason why I had toimportit.The correct way to do what I wanted:
And then calling
p.printProxybehaves like I wanted it to behave (becauseprintProxyis insideIntPrinter‘s scope.)