Back2Basics: Currying Function in Scala

Reading Time: 2 minutes

Normally we write function and it seems like below:

def multiplySimple(a: Int, b: Int): Int = a * b

We declare a function with all the arguments needed inside a single parameter list.

In currying however, we can split this parameter list into multiple parameter lists.

def multiplyCurry(a: Int)(b: Int): Int = a * b

For example, we could split the parameter list into multiple where each list just takes one parameter. However, the function body in both cases remains the same.

Also, the way we call the function changes, instead of passing all the arguments together, we pass them as required by the curried function.

val b = multiplyCurry(2)(10)

val c = multiplyCurry(2) _
val d = c(10)

There is an interesting thing to note when we declare the curried function, what we get back is not one function, rather, two traditional function invocations back-to-back.

Let’s see the return type of multiplyCurry.

multiplyCurry(a: Int)(b: Int)

The first function takes the integer argument and returns the Function Value for the second function.

multiplyCurry(a: Int)(b: Int)

This second function takes the integer parameter and applies to the Function Value.

The final result of what we get from curried function is very similar to what we can get by writing a function that returns a Function Literal.

val c = multiplyCurry(2) _

As we see in case of this, we have partially applied the function by passing underscore (_) as a proxy to the second parameter list. Here, the variable “c” refers to the second Function Value. We have confirmed that by applying the same argument 10 and comparing the result of “d” with “b”, and they both result in the same value.

That all from this blog! Keep learning, keep growing!!!!

 

Knoldus-blog-footer-image

Written by 

Sarfaraz Hussain is a Big Data fan working as a Software Consultant with an experience of 1+ years. He is working in technologies like Spark, Scala, Java, Hive & Sqoop and has completed his Master of Engineering with specialization in Big Data & Analytics. He loves to teach and is a huge fitness freak and loves to hit the gym when he's not coding.

1 thought on “Back2Basics: Currying Function in Scala2 min read

Comments are closed.