Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How comes my implicit gets shadowed by a method parameter?

Given the following code :

case class W(s:String)
object W{
  implicit lazy val w=W("w")
}
trait A{
  implicit def a:W=W("a")
}
object B{
  def implicitUser(implicit w:W)=println(w.toString)
}
object Auser extends A{
  def testa(a:String="0")=B.implicitUser
  def testb(b:String="0")=B.implicitUser
}

How do you explain the following output of the repl

scala>Auser.testa()
W(w)

scala>Auser.testb()
W(a)

It looks like the method parameter name in testa prevents the resolution of the implicit named a. (scala 2.10.3)

like image 509
Jean Avatar asked Jun 29 '26 14:06

Jean


1 Answers

Implicits are, in addition to being implicit, just identifiers.

This means you can shadow them by using another identifier with the same name.

def foo(i: String) {
  for (i <- 0 to 3) { println(i) }   // Outer i is hidden
}

def foo(implicit i: String) {
  for (i <- 0 to 3) { println(i) }   // Outer i is still hidden
}

def bar(implicit i: String) { println("Bar "+i) }

def foo(implicit i: String) { bar }  // Works

def foo(implicit i: String) {
  for (i <- 0 to 3) bar              // Doesn't
}
like image 53
Rex Kerr Avatar answered Jul 02 '26 12:07

Rex Kerr