Higher-Order Functions
A higher-order function either takes another function as an input or gives one back, like a coach who hands out a play to run. It lets you treat actions like ordinary values.
In this page:
Syntax
def function_name(f: InputType => OutputType, value: InputType): OutputType = f(value)
def returns_function(): InputType => OutputType = (x: InputType) => expression
Higher-Order Functions
A higher-order function either takes another function as a parameter, returns a function, or both -- functions are first-class values in Scala, storable and passable just like any other value.
This is the foundation of Scala's functional programming style, letting you parameterize behavior itself, not just data. Many standard collection methods, like map and filter, are higher-order functions.
Note:
The function type
Int => Int describes a function taking an Int and returning an Int, usable as a parameter type.Example: Higher-Order Functions
object Main extends App {
def applyTwice(f: Int => Int, x: Int): Int = {
f(f(x))
}
def addOne(n: Int): Int = n + 1
println(applyTwice(addOne, 5))
}
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
- Passing a method result instead of the method itself, as in
applyTwice(addOne(1), 5), when a function is expected. - Getting the type wrong, such as
f: Int => Intwhile passing a function that takes two arguments. - Forgetting the return type of the function parameter, making the higher-order function hard to read.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: