How does implicitly work in this example from Scala in Depth

假装没事ソ 提交于 2019-12-23 02:48:28

问题


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)
}


来源:https://stackoverflow.com/questions/13773964/how-does-implicitly-work-in-this-example-from-scala-in-depth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!