2012-12-08 27 views
1

在Scala深度书。有隐含作用域的这个例子如下:隐藏在这个例子中从斯卡拉深入工作

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

看一看http://stackoverflow.com/questions/3855595/scala-identifier-隐含,看看是否解决你的问题? – huynhjl

回答

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