score:1

Accepted answer

Indeed it's the correct behaviour. implicit values are only searched in current scope and calling print outside IntPrinter means it's not on the class scope (obviously) and the reason why I had to import it.

The correct way to do what I wanted:

case class IntPrinter(implicit val i: Int) {
  def print()(implicit i: Int) = println(i)
  def printProxy() = print()
}

And then calling p.printProxy behaves like I wanted it to behave (because printProxy is inside IntPrinter's scope.)

score:1

I'm not sure I understand. Why is it that you need implicits here at all? It seems that you could just as easily do this:

scala> case class IntPrinter(i: Int) { def print() = println(i) }
defined class IntPrinter

scala> val p = IntPrinter(9)
p: IntPrinter = IntPrinter(9)

scala> p.print()
9

or, if you really have use for IntPrinter taking an implicit:

scala> case class IntPrinter(implicit val i: Int) { def print() = println(i) }
defined class IntPrinter

scala> val p = IntPrinter()(9)
p: IntPrinter = IntPrinter(9)

scala> p.print()
9

Basically, in that case, you need not specify that it is implicit twice; when you declared it implicit the first time, that made i a member of the class, so you can continue to reference it throughout the rest of the class—just like you could with any other data member of a class.


Related Query

More Query from same tag