2016-07-22 18 views
1

在下面的Scala片段中,我的目標是爲某些類Collector字面上寫Collector { "A" x 123 }。這個匿名子類的主體應該可以訪問類Collector中定義的隱式x。 我試圖通過一個伴侶對象和一個名稱參數來實現此目的,但沒有成功。 現在我必須寫new Collector { "A" x 123 }。你能找到一種方法來擺脫new關鍵字嗎?Scala - 從匿名子類訪問隱式類,不使用新關鍵字

object TestApp extends App { 
    new Collector { "A" x 123 } // works as intended, even without companion object 
    Collector { "A" x 123 } // does not compile because no implicit "x" found 
} 

class Collector { // some class with an individual implicit inner class 
    val coll = ArrayBuffer.empty[String] 
    implicit class MyImplicit(name: String) { def x(i: Int) = coll += s"$name($i)" } 
} 

object Collector { // getting rid of the "new" keyword looses access to MyImplicit 
    def apply(body: => Unit) = new Collector { body } 
} 

回答

1

Collector { "A" x 123 }不創建的Collector一個匿名子類,它只是一個方法調用。所以你不能在論證中訪問Collector的成員,無論是否隱含。

+1

啊,我明白了,這甚至與暗示有關,但更多的是關閉和名義參數。並且可能沒有解決方法(沒有宏)。現在我看到我試圖沿着兩個躍點將字面正文「{」A「x 123}」轉發到不同的上下文中(我期望最終限制自由變量)。但它反過來:*首先*所有自由變量都在它們被直接寫入的地方是有界的,所以即使傳遞了一些閉包,它也只會引用它的原始上下文。 –

+0

是的,確切地說。 –