← Back to Scala Course | Chapter 9: Functional Programming | Lesson 5 of 8

Currying

Currying breaks a function with many inputs into a chain of steps that each take one, like ordering a pizza size first and toppings next. You can give inputs in stages.

In this page:

  1. Currying
Syntax
scala
def function_name(a: Type)(b: Type): ReturnType = expression

function_name(value1)(value2)

Currying

A curried function is declared with multiple parameter lists, like def add(a: Int)(b: Int): Int, letting you call it with all arguments at once or apply them one list at a time.

Calling it with only the first parameter list returns a new function expecting the remaining ones. Currying is useful for building reusable, partially-configured functions and works especially well with Scala's syntax for passing a trailing function argument as a block.

Note: Curried functions are what enable Scala's block-syntax method calls, like list.foldLeft(0) { (acc, x) => acc + x }.

Example: Currying

markup
object Main extends App {
  def add(a: Int)(b: Int): Int = a + b

  println(add(3)(4))

  val addFive = add(5) _
  println(addFive(10))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling add(3, 4) on a curried method, which gives an error because it has two parameter lists.
  2. Writing add(5) without _ in Scala 2 and getting a missing argument list error.
  3. Confusing currying with default parameters, when currying splits a function into steps.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.