2013-10-26 90 views

回答

10

是的,這是可能的。

當你有標記爲implicit第二令行禁止參數,功能似乎是類型不是

Int => (MyClass => Result) => ResultOfFunction 

它是如果咖喱高階函數的參數是一個普通參數;相反,它看起來像這樣:

Int => ResultOfFunction 

這裏有一個簡單的例子:

scala> def curriedFn(i : Int)(implicit func : String => Int) : Boolean = (i + func("test!")) % 2 == 0 
curriedFn: (i: Int)(implicit func: String => Int)Boolean 

scala> implicit val fn : String => Int = s => s.length 
fn: String => Int = <function1> 

scala> curriedFn _ 
res4: Int => Boolean = <function1> 

正如你所看到的,implicit參數得到了 '淘汰'。爲什麼和如何?這是一個比我更有知識的人的問題。如果我不得不猜測,我會說編譯器直接用隱式值替換參數,但這很可能是錯誤的。

反正離題不談,這裏是你的情況非常相關的一個例子:

scala> def foo(func : Int => Boolean) = if(func(3)) "True!" else "False!" 
foo: (func: Int => Boolean)String 

scala> foo(curriedFn) 
res2: String = True! 

現在,如果第二個函數參數不隱:

scala> def curriedNonImplicit(i : Int)(fn : String => Int) : Boolean = (i + fn("test!")) % 2 == 0 
curriedNonImplicit: (i: Int)(fn: String => Int)Boolean 

scala> curriedNonImplicit _ 
res5: Int => ((String => Int) => Boolean) = <function1> 

正如你所看到的,類型的功能有點不同。這意味着,該解決方案將有不同太:

scala> def baz(func : Int => (String => Int) => Boolean) = if(func(3)(s => s.length)) "True!" else "False!" 
baz: (func: Int => ((String => Int) => Boolean))String 

scala> baz(curriedNonImplicit) 
res6: String = True! 

你必須直接指定函數的方法中,因爲它不是隱含之前提供。

+0

感謝您用完整的例子來解釋這兩種情況(有和沒有隱含的)。 – Prasanna