Easy Tutorial
❮ Functions Variable Arguments Scala Regular Expressions ❯

Scala Function Currying

Scala Functions

Currying refers to the process of transforming a function that originally accepts two parameters into a new function that accepts one parameter. The new function returns a function that takes the original second parameter as its argument.

Example

First, let's define a function:

def add(x: Int, y: Int) = x + y

We should use it like this: add(1, 2)

Now, let's transform this function:

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

We should use it like this: add(1)(2). The final result is still 3, and this method (process) is called currying.

Implementation Process

add(1)(2) is actually a sequence of calls to two regular functions (non-curried functions). The first call uses one parameter x and returns a function type value. The second call uses the parameter y to invoke this function type value.

Essentially, it first evolves into such a method:

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

What does this function mean? It takes an x as a parameter and returns an anonymous function, which is defined as: takes an Int type parameter y, and the function body is x + y. Now let's call this method.

val result = add(1)

A result is returned, and the value of result should be an anonymous function: (y: Int) => 1 + y

So to get the result, we continue to call result.

val sum = result(2)

The final printed result is 3.

Complete Example

Here is a complete example:

object Test {
  def main(args: Array[String]) {
    val str1: String = "Hello, "
    val str2: String = "Scala!"
    println("str1 + str2 = " + strcat(str1)(str2))
  }

  def strcat(s1: String)(s2: String) = {
    s1 + s2
  }
}

Execute the above code, and the output result is:

$ scalac Test.scala
$ scala Test
str1 + str2 = Hello, Scala!

Scala Functions

❮ Functions Variable Arguments Scala Regular Expressions ❯