Scala Curried or currying functions

52 total views, 1 views today

Welcome to Scala series. In this tutorial, you will learn about Scala Curried or currying functions in detail.

Usually a method or a function can have N number of arguments.

Example

def add(a: Int, b: Int): Int = {
a + b
}

Result : 4

The above function/method has two arguments a and b.

Curried or Currying functions

In Scala, a method/function can also have multiple parameters list which called as currying functions or curried functions.

def add(x: Int) = (y: Int) => {
x + y
}

The above function/method accepts two list of arguments x and y. The method should be invoked as below.

Result : 4

Curried or Currying functions examples

def add2(x: Int) = (y: Int) => (z: Int) => (a: Int) => {
x + y + z + a
}

Result : 10

def add3(x: Int) = (y: Int, z: Int) => (a: Int) => (b: Int) => {
x + y + z + a + b
}

Result : 15

I hope you like this mini tutorial and you were able to understand how Curried or currying functions works.

Thanks for reading and please give us a thumb up and comment below!

Tags : 