Showing posts with label Currying. Show all posts
Showing posts with label Currying. Show all posts

Saturday, April 7, 2018

Currying in Scala

Currying is one of the several mechanisms in Scala to create control abstractions.

Common way of writing function is as:

def plainCommonSum(x: Int, y: Int) = x + y
This function has a single parameter list.

A curried function, on other hand, is applied to multiple argument lists. Above function when written in 'curried' manner:

def curriedSum(x: Int)(y: Int) = x + y
An invocation to a curried function is basically a sequence of traditional function invocations.For example, when we call 'curriedSum' ,first a function call takes a single Int parameter 'x', and returns a function value. A second function call is made with this function value and it takes a single Int parameter 'y',and returns an Int.

We can get reference to 'second' function by using placeholder notation.

def greetSomeOne(greeting: String)(name: String) =  greeting + " " +name
val greetHi = greetSomeOne("Hi")_ 
val greetHello = greetSomeOne("Hello")_
       println(greetHi("World"))
println(greetHello("World")) 

Output is:
Hi World
Hello World