简体   繁体   中英

Scala implicit parameter scope

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!

Your code should work and it does work for me.

Did you by chance type that in the REPL? If so, there is something special concerning 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, and not part of the implicit scope). In the REPL, there are no files, but the class and its companion object must be defined at the same time. To do that, you must enter them in paste mode.

Type :paste , then paste (or just type) at least both the object Widget and the class Widget (you may paste the rest to the code at the same time, but it is not necessary), and then CTRL-D . That should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM