scala - Why should calling a currying function with non-complete args with underscore -
according scalabyexample:
a curried function definition def f (args1) ... (argsn) = e n > 1 expands to
def f (args1) ... (argsn−1) = { def g (argsn) = e ; g }
or, shorter, using anonymous function:
def f (args1) ... (argsn−1) = ( argsn ) => e
uncurried version:
def f(x: int): int => int = { y: int => x * y } //> f: (x: int)int => int def f1 = f(10) //> f1: => int => int f1(5)
curried version:
def g(x: int)(y: int) = { x * y } //> g: (x: int)(y: int)int def g1 = g(10) _ //> g1: => int => int g1(5)
the question is, why curried required underscore in line #5 in second code snippet.
you can find explanation @ martin odersky book: http://www.artima.com/pins1ed/functions-and-closures.html (search "why trailing underscore").
in short because scala closer java in lot of things, rather functional languages not required. helps find out mistakes @ compile time, if forgot missing argument.
if underscore not required, next code compile:
println(g(10))
and check helps preventing such mistakes
there cases though, when such calls obvious, , underscore not required:
def g(x: int)(y: int) = { x * y } def d(f: int => int) { f(5) } d(g(10)) // no need write d(g(2) _) // or other way can specify correct type val p: int => int = g(10)
Comments
Post a Comment