Higher-Order Functions
In this page:
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
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: