I wanted to clarify benefits about currying in scala. According to "Programming in Scala Second Edition" - "currying A way to write functions with multiple parameter lists. For instance
def f(x: Int)(y: Int)
is a curried function with two parameter
lists. A curried function is applied by passing several arguments
lists, as in: f(3)(4)
. However, it is also possible to write a partial
application of a curried function, such as f(3)." "c"
One benefit connected with creation partially applied functions like this
def multiplyCurried(x: Int)(y: Int) = x * y
def multiply2 = multiplyCurried(2) _
But we also can use partially applied functions without currying
def multiplyCurried(x: Int,y: Int)
def multiply2 = multiplyCurried(2, _)
Could you please give a few example, where currying will show benefits ?
Curry functions become really useful when you have implicit parameters.
Take for example the map function on futures:
map[S](f: (T) ⇒ S)(implicit executor: ExecutionContext): Future[S]
The second parameter is implicit, and this definition allows you to write expressions like
val f2 = f1.map(x => x)
when you have the implicit value in scope.
Another place where curry is useful is a common pattern in the Scala code where you would like to pass a function to a method (it may be a callback function, for instance).
Take for example the "loan" pattern for input streams, that allow you to use a stream without thinking about proper closing the resource
def withInputStream[T](opener: => InputStream)(f: InputStream => T): T = ...
withInputStream(new InputStream("hello.txt")) { inputStream =>
readLines(inputStream)
}
This kind of syntax makes the code clearer in a lot of cases
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