Scala Functions as Values
Define a method and pass it to a higher-order function.
On this page
Scala basics.
- Define a method and pass it to a higher-order function.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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))
}
}25 81
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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)) }}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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How Scala processes this code
Scala compiles for the JVM, which invokes the main entry point.
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.