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
}

add(1,3)


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.

add(1)(3)

Result : 4

Curried or Currying functions examples

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

add2(1)(2)(3)(4)

Result : 10

 

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

add3(1)(2,3)(4)(5)

Result : 15

References : Scala Curried or currying functions documentation

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 :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.