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:
Syntax
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
object Main extends App {
def add(a: Int)(b: Int): Int = a + b
println(add(3)(4))
val addFive = add(5) _
println(addFive(10))
}
Login to try C/C++/Java/PHP code in the editor
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
- Calling
add(3, 4)on a curried method, which gives an error because it has two parameter lists. - Writing
add(5)without_in Scala 2 and getting amissing argument listerror. - 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: