Scala Functions as Values

Define a method and pass it to a higher-order function.

Scala
object Main {
  def square(n: Int): Int = n * n

  def main(args: Array[String]): Unit = {
    val twice = (f: Int => Int, x: Int) => f(f(x))
    println(square(5))
    println(twice(square, 3))
  }
}
Output
25
81

Explanation

def square(n: Int): Int = n * n defines a method whose body is a single expression. In Scala functions are values: a function of type Int => Int can be stored in a variable or passed as an argument.

twice takes a function f and a value x and applies f two times. Passing the method square where a function is expected works because Scala converts the method into a function automatically. twice(square, 3) is therefore square(square(3)) = 81.

Explore the dry run
Guided walkthroughReady
1object Main {
2 def square(n: Int): Int = n * n
3
4 def main(args: Array[String]): Unit = {
5 val twice = (f: Int => Int, x: Int) => f(f(x))
6 println(square(5))
7 println(twice(square, 3))
8 }
9}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
A method with an expression body.—
—
A function value that applies another function two times.—
—
Call the method directly.—
25
square(3) is 9, then square(9) is 81.inner = 9, result = 81
25
81

Cost and common mistakes

O(1) time and space.

  • Int overflow wraps silently, so squaring large numbers gives wrong results.
  • The last expression is the return value; adding a stray statement after it changes the result.

Try it yourself

Predict twice(square, 2).

Reveal answer and reasoning

square(2) is 4 and square(4) is 16.

Further reading