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

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:

  1. Higher-Order Functions
Syntax
scala
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

markup
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))
}
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. Passing a method result instead of the method itself, as in applyTwice(addOne(1), 5), when a function is expected.
  2. Getting the type wrong, such as f: Int => Int while passing a function that takes two arguments.
  3. 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:

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.