How does implicitly work in this example from Scal

2019-06-05 00:38发布

问题:

In the book Scala in Depth . There's this example of implicit scoping as follows:

scala> object Foo {
     | trait Bar
     | implicit def newBar = new Bar {
     |   override def toString = "Implicit Bar"
     | }
     | }
defined module Foo

scala> implicitly[Foo.Bar]
res0: Foo.Bar = Implicit Bar

My question here is how did implicitly find the implementation of the trait Bar in the above given example? I think I am a little confused by how implicitly works

回答1:

Apparently, for Foo.Bar, it works like Foo#Bar, i.e., if T is a type projection S#U, the parts of S as well as T itself are in implicit scope (7.2 of the spec, but see usual resources on implicit scope, such as you're already consulting). (Update: Here is such a resource. It doesn't illustrate exactly this case, and whether a real example would look as artificial.)

object Foo {
  trait Bar
  implicit def newBar = new Bar {
    override def toString = "Implicit Bar"
  }
}

class Foo2 {
  trait Bar
  def newBar = new Bar {
    override def toString = "Implicit Bar"
  }
}
object Foo2 {
  val f = new Foo2
  implicit val g = f.newBar
}

object Test extends App {
  // expressing it this way makes it clearer
  type B = Foo.type#Bar
  //type B = Foo.Bar
  type B = Foo2#Bar
  def m(implicit b: B) = 1
  println(implicitly[B])
  println(m)
}