Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of currying in Scala

Tags:

scala

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 ?

like image 890
initmax Avatar asked Oct 20 '22 20:10

initmax


1 Answers

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

like image 129
Marius Danila Avatar answered Oct 29 '22 22:10

Marius Danila