I'm trying to figure out how to use currying in Scala.
In the following snippet:
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))
}
}
the definitions for f
and g
work, the one for h
does not:
/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)
What's the reasoning behind this being illegal? It seems to me that Scala should be able to figure out that after calling foo(1)(2)
you'd be left with an Int => Int
.
This is intended. If it were allowed (some languages really allow that), that would make it work when you forget to put an argument, and instead of compile-time error you would expect. This happens so often that scala authors decide to trade-off here and disallow this notation.
Martin told about that in his book, see "Why the trailing underscore?" http://www.artima.com/pins1ed/functions-and-closures.html#8.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With