Skip to content
AgileLogics
5 min read

Functions as Values

Prerequisites: Methods

In Scala, functions are values: you can store them, pass them to other functions, and return them.

@main def functions(): Unit =
  val double = (x: Int) => x * 2
  val add: (Int, Int) => Int = (a, b) => a + b

  println(double(21))
  println(add(2, 3))
42
5
  • (x: Int) => x * 2 is a function literal (a lambda).
  • (Int, Int) => Int is a function type: takes two Ints, returns an Int.

Passing functions to methods

This is where functions as values pay off:

@main def passing(): Unit =
  val numbers = List(1, 2, 3, 4, 5)

  println(numbers.map(x => x * 10))
  println(numbers.filter(x => x % 2 == 1))
  println(numbers.map(_ * 10))
  println(numbers.filter(_ > 2).map(_.toString).mkString("-"))
List(10, 20, 30, 40, 50)
List(1, 3, 5)
List(10, 20, 30, 40, 50)
3-4-5

_ is placeholder syntax: _ * 10 means x => x * 10. Each _ stands for the next parameter, so it's only for short, simple lambdas.

Methods become functions

A method can be passed wherever a function is expected:

def square(n: Int): Int = n * n

def applyTwice(f: Int => Int, x: Int): Int = f(f(x))

@main def methodsAsFunctions(): Unit =
  println(List(1, 2, 3).map(square))
  println(applyTwice(square, 3))
  println(applyTwice(_ + 10, 1))
List(1, 4, 9)
81
21

applyTwice is a higher-order function — it takes a function as a parameter. Level 2 covers these in depth.