Skip to content

Scala Partially Applied Function!

At this moment I do not have a personal relationship with a computer.

Janet Reno

In Scala, a partially applied function is a function that is created by specifying only some of the arguments of a function. A partially applied function is a function that takes fewer arguments than the original function, but still returns a function that can be called with the remaining arguments.

Here’s an example of a partially applied function in Scala:

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

val add2 = add(_: Int, 2, _: Int)

val result = add2(1, 3)
println(result) // Output: 6

In this example, add is a function that takes three integer arguments and returns their sum. We can create a partially applied function add2 by specifying only the second argument of the add function, using the underscore _ to indicate that we are not providing a value for that argument yet. The resulting function takes two integer arguments and returns their sum, by adding the value 2 to the second argument.

When we call the add2 function with the arguments 1 and 3, it returns the expected result of 6. This is because the first and third arguments are passed to the add2 function, and the value 2 is already provided by the partially applied function.

Partially applied functions can be useful when we want to create new functions that are based on existing functions, but with some of the arguments already filled in. They can simplify the syntax of function calls, and reduce the amount of code needed to define new functions.

Note that partially applied functions are different from curried functions, which are functions that return other functions. Partially applied functions are created by passing arguments to an existing function, while curried functions are created by defining a function that takes a single argument and returns another function that takes the next argument.

Published inPersonal PostsScalaTechnical Posts