如何在Scala in Depth中隐式使用此示例

时间:2012-12-08 02:49:26

标签: scala implicit-conversion traits

在Scala in Depth一书中。这个隐式范围的例子如下:

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

我的问题是如何在上面给出的例子中隐式找到特征栏的实现?我觉得我对隐含的工作有点困惑

1 个答案:

答案 0 :(得分:3)

显然,对于Foo.Bar,它的工作方式与Foo#Bar类似,即if T is a type projection S#U, the parts of S as well as T itself处于隐式范围内(规范的7.2,但请参阅隐式范围的常用资源,例如您已经在咨询) 。 (更新:Here is such a resource.它没有完全说明这种情况,以及一个真实的例子是否看起来像是人为的。)

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