2014-09-04 50 views
0

我想不通爲什麼這不起作用:應用功能與隱參數需要明確的說法

case class Expression extends Node[Doube] { 

    def apply(implicit symbolTable: Map[String,Double]) = value 
} 

注意值在節點定義,也有一個隱含的符號表的說法。

當我嘗試調用它像這樣:

implicit val symbolTable = Map("a"->1, "b"->2) 
//and x is an Expression, then: 

x() // does not compile (can't find implicit) but 
x(symbolTable) // works fine 

和奇怪:

x.value // works fine too 

如果我寫申請,像這樣:

def apply()(implicit symbolTable: Map[String,Double]) 

它的工作原理,但我不不明白爲什麼我需要這樣做......

任何指針?

回答

1

spec區分價值轉換和方法轉換。

x是一個值。對於兩個參數列表的示例,x()是一種帶有一個參數列表的方法類型,它是隱式提供的隱式列表。

對於您的原始示例,使用一個隱式參數列表,x()未能提供所需的arg。 (不是「隱含未找到」。)

scala> def f(implicit s: String) = 42 
f: (implicit s: String)Int 

scala> f 
<console>:9: error: could not find implicit value for parameter s: String 
       f 
      ^

scala> f() 
<console>:9: error: not enough arguments for method f: (implicit s: String)Int. 
Unspecified value parameter s. 
       f() 
      ^

對於要提供的含義,您不得提供參數列表。

對於你奇怪的x.value,顯然value是一個帶有一個隱含參數列表的方法。

更多:

scala> object x { def apply(implicit s: String) = 42 } 
defined object x 

scala> x.apply 
<console>:9: error: could not find implicit value for parameter s: String 
       x.apply 
       ^

scala> implicit val s: String = "hi" 
s: String = hi 

scala> x.apply 
res1: Int = 42 

scala> x() 
<console>:10: error: not enough arguments for method apply: (implicit s: String)Int in object x. 
Unspecified value parameter s. 
       x() 
      ^

當你寫x.apply如上所述,它要麼供應括號把它變成一個應用程序,提供隱性ARGS,或嘗試,如果上下文希望是把它變成一個功能。

+0

是的,value是一個帶有一個隱式參數列表的方法,但是它也適用,爲什麼它們的行爲不一樣? – fsauer 2014-09-04 14:56:09

+0

你沒有在任何地方寫'x.apply'。 – 2014-09-04 15:04:29

+0

是不是x()調用? – fsauer 2014-09-05 19:34:39