Partial Application
Partial application fixes some inputs of a function ahead of time and leaves the rest for later, like a form with some blanks pre-filled. You get a new simpler function back.
In this page:
Syntax
def function_name(a: Type, b: Type): ReturnType = expression
val partial = function_name(value1, _: Type)
partial(value2)
Partial Application
Partial application fixes some of a function's arguments upfront, producing a new function that only needs the remaining ones, using the _ placeholder for unfixed positions, like add(5, _: Int).
This is closely related to currying but works on ordinary (non-curried) multi-parameter functions too. It's a way to specialize a general function into a more specific one without writing new code.
Note:
Partial application with
_ works on regular multi-parameter functions, not just curried ones with multiple parameter lists.Example: Partial Application
object Main extends App {
def add(a: Int, b: Int): Int = a + b
val addFive: Int => Int = add(5, _: Int)
println(addFive(10))
println(addFive(20))
}
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
- Writing
add(5)and expecting a function, when for partial application you must supply a placeholder such asadd(5, _: Int). - Leaving out the type of the placeholder, so the compiler cannot infer the parameter type.
- Confusing partial application with currying, when currying needs the method to be declared with several parameter lists.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: