[英]Scala currying and type inference
我試圖弄清楚如何在Scala中使用currying。
在以下代碼段中:
object Foo {
def foo(a:Int)(b:Int)(c:Int) : Int = a + b + c
def main(a:Array[String]) {
val f = foo(1)(2) _
def g : Int => Int = foo(1)(2)
// def h = foo(1)(2)
println(f(3))
println(g(3))
// println(h(3))
}
}
對於定義f
和g
工作時,一個h
不會:
/home/vlad/Desktop/b.scala:9: error: missing arguments for method foo in object Main;
follow this method with `_' if you want to treat it as a partially applied function
def h = foo(1)(2)
這是非法的原因是什么? 在我看來,Scala應該能夠弄清楚在調用foo(1)(2)
你會得到一個Int => Int
。
這是有意的。 如果它被允許(某些語言確實允許),那么當你忘記放置一個參數時,這將使它工作,而不是你期望的編譯時錯誤。 這種情況經常發生,scala作者決定在這里進行權衡並禁止這種表示法。
馬丁在他的書中講到了這一點,請參閱“為什么尾隨下划線?” http://www.artima.com/pins1ed/functions-and-closures.html#8.7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.