Currying in Scala

In a nutshell, currying is the process of decomposing a function of multiple arguments into a chained sequence of functions of one argument.

In pseudocode, this means that an expression like this:
f1 = f(x) f2 = f1(y) result = f2(z)

def multiply (a, b) {
return a * b
}

multiply(3, 4) // returns 12
This is a function that takes two arguments, a and b, and returns their product. We will now curry this function:

def multiply (a) = {
def multiply1(b) {
return a * b
}
}
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their product.

multiply(3)(4) //This returns 12, like the multiply(3, 4) statement.

var multiply3 = multiply(3)// It returns the function that takes the other argument b

multiply3(4) // It returns 12

Leave a Reply

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