在Scala中,爲什麼咖喱函數可以很容易地直接傳遞給其他函數,但是當將它分配給val
時,還需要將其部分應用於_
?例如,給出的兩個功能:爲什麼Scala在分配給val時需要部分應用curried函數?
def curried(a: Int)(b: Int) = a + b
def test(a: Int, f: Int => Int) = f(a)
我可以很容易地通過curried
到test
有:
test(5, curried(5))
,一切都是幸福的。但是,如果我只需撥打curried(5)
我得到一個錯誤:如果我改變呼叫但是包括類型信息
scala> curried(5)
<console>:9: error: missing arguments for method curried;
follow this method with `_' if you want to treat it as a partially applied function
curried(5)
,它的工作原理:
val 'curried: Int => Int = curried(5)
任何人都可以解釋的合理不一致的背後,想必給定原始方法的類型定義,Scala編譯器可以推斷函數爲Int => Int
?
在'val'的情況下,如果你給一個類型註解,你將不需要公開的部分應用程序'_'。 – 2013-03-08 23:19:58