Monday 21 September 2020

Scala: Currying

Currying is a process of transforming multi argument functions into a function that takes just a single argument.

 

For example, we can write a function that takes two integers as argument and return the sum like below.

 

def incBy(x: Int) = (y : Int) => x + y

 

Below snippet calculate sum of two integers 10 and 20.

incBy(10)(20)

 

10 is passed as first argument (x) and 20 is passed as 2nd argument (y)

scala> def incBy(x: Int) = (y : Int) => x + y
def incBy(x: Int): Int => Int

scala> 

scala> incBy(10)(20)
val res25: Int = 30

 

We can define other functions from incBy function.

scala> def incBy1 = incBy(1)
def incBy1: Int => Int

scala> incBy1(10)
val res26: Int = 11

scala> incBy1(23)
val res27: Int = 24

Scala provide simple way to define currying functions

For example, same incBy function we can define like below.

 

def incBy(x: Int)(y:Int) = x + y

def incBy1(a: Int) = incBy(1)(a)

scala> def incBy(x: Int)(y:Int) = x + y
def incBy(x: Int)(y: Int): Int

scala> def incBy1(a: Int) = incBy(1)(a)
def incBy1(a: Int): Int

scala> incBy1(10)
val res28: Int = 11

scala> incBy1(23)
val res29: Int = 24

 

 

 


 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment