2012-12-08 65 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) 
}