Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Currying in Scala

What is Currying?

Currying is a technique in functional programming that transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This allows for partial application of functions, which can lead to more modular and reusable code.

Why Use Currying?

The main benefits of currying include:

  • Partial Application: You can create new functions by fixing some arguments of a function.
  • Higher-Order Functions: Currying allows functions to return other functions, enabling more flexible and reusable code structures.
  • Enhanced Readability: Currying can help in creating more readable code by breaking down complex functions into simpler, single-argument functions.

Basic Example of Currying in Scala

Let's start with a basic example of a curried function that adds two numbers.

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

This function can be called with two parameters:

add(2)(3) // Returns 5

In the example above, the function add takes two parameters, but it is defined in a way that allows it to be called with one argument at a time.

Partial Application with Currying

When you partially apply a curried function, you can create a new function with some of the parameters already set. For instance:

val addTwo = add(2)_

This creates a new function addTwo that adds 2 to its argument:

addTwo(3) // Returns 5

Currying with Multiple Parameters

Currying can also be applied to functions that take more than two parameters. Consider a function that concatenates three strings:

def concat(a: String)(b: String)(c: String): String = a + b + c

This function can be called as follows:

concat("Hello, ")("World")("!") // Returns "Hello, World!"

Real-World Example: Currying in Action

Let's see a more practical example where currying can be beneficial. Assume we have a function to calculate the price of a product with tax:

def priceWithTax(taxRate: Double)(price: Double): Double = price + (price * taxRate)

We can create a function for a specific tax rate:

val priceWithVAT = priceWithTax(0.2)_

Now we can easily calculate prices:

priceWithVAT(100) // Returns 120.0

Conclusion

Currying is a powerful concept in functional programming that enhances the flexibility and readability of code. By transforming functions into a chain of single-argument functions, we can easily create new functions through partial application and improve code reusability. Understanding currying can significantly benefit your programming practices in Scala.