1

在 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

我的问题是如何在上面给出的示例中隐式找到特征 Bar 的实现?我想我对隐式的工作方式有点困惑

4

1 回答 1

3

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

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)
}
于 2012-12-08T03:58:06.230 回答