TExcelTAD
Home › Scala › Scala Lambdas

Scala Lambdas

A lambda (also called an anonymous function or function literal) is a function without a name, written directly where it is needed. Lambdas are everywhere in Scala because collection methods like map, filter and sortBy take them as arguments.

Writing a lambda

The syntax is (parameters) => body:

scala · try it yourself
@main def run(): Unit =
  val double = (x: Int) => x * 2
  val add = (a: Int, b: Int) => a + b
  val hello = () => "hello"

  println(double(21))
  println(add(3, 4))
  println(hello())
42
7
hello

double is a value of type Int => Int — it can be stored, passed to other functions and returned from them, just like a number or a string.

Function types

Lambda Type
() => 42 () => Int
(s: String) => s.length String => Int
(a: Int, b: Int) => a * b (Int, Int) => Int
(n: Int) => println(n) Int => Unit

When the expected type is known, you can leave out the parameter types:

scala · try it yourself
@main def run(): Unit =
  val isEven: Int => Boolean = n => n % 2 == 0
  val numbers = List(5, 8, 13, 20)
  println(numbers.filter(n => n > 10))
  println(numbers.map(n => n * 10))
  println(numbers.filter(isEven))
List(13, 20)
List(50, 80, 130, 200)
List(8, 20)

The underscore shorthand

If each parameter is used exactly once, in order, you can replace it with _:

scala · try it yourself
@main def run(): Unit =
  val words = List("kiwi", "banana", "fig", "cherry")
  println(words.map(_.length))
  println(words.filter(_.startsWith("c")))
  println(words.sortBy(_.length))
  println(List(1, 2, 3, 4).reduce(_ + _))
List(4, 6, 3, 6)
List(cherry)
List(fig, kiwi, banana, cherry)
10

_ + _ means (a, b) => a + b: the first underscore is the first parameter, the second is the second.

Tip: Use _ for short, obvious lambdas. As soon as you need the parameter twice or the body gets longer, give it a real name.

Multi-line lambdas

Use braces or indentation for a body with several lines. The last expression is the result.

scala · try it yourself
@main def run(): Unit =
  val prices = List(12.0, 48.5, 99.99)
  val labels = prices.map { p =>
    val discounted = if p > 40 then p * 0.9 else p
    f"$p%.2f -> $discounted%.2f"
  }
  labels.foreach(println)

  val totals = prices.map: p =>
    val withTax = p * 1.2
    math.round(withTax * 100) / 100.0
  println(totals)
12.00 -> 12.00
48.50 -> 43.65
99.99 -> 89.99
List(14.4, 58.2, 119.99)

The second form uses Scala 3's colon syntax for passing a lambda as the last argument without braces.

Closures

A lambda can use variables from the scope where it was created. It "closes over" them, which is why such a lambda is called a closure.

scala · try it yourself
def makeMultiplier(factor: Int): Int => Int =
  (x: Int) => x * factor

@main def run(): Unit =
  val triple = makeMultiplier(3)
  val tenTimes = makeMultiplier(10)
  println(triple(7))
  println(tenTimes(7))

  var calls = 0
  val counted = (s: String) =>
    calls += 1
    s.reverse
  println(List("abc", "xyz").map(counted))
  println(s"calls = $calls")
21
70
List(cba, zyx)
calls = 2

Turning methods into functions

A method can be used wherever a function is expected; Scala converts it automatically (this is called eta-expansion).

scala · try it yourself
def shout(s: String): String = s.toUpperCase + "!"

@main def run(): Unit =
  val f = shout       // method turned into a String => String value
  println(List("hi", "bye").map(shout))
  println(f("wow"))
  val composed = ((s: String) => s.trim).andThen(shout)
  println(composed("  hey  "))
List(HI!, BYE!)
WOW!
HEY!

Test yourself

What is the type of (s: String) => s.length?

  1. String
  2. Int
  3. String => Int
  4. Int => String

What does List(1, 2, 3).map(_ * 2) return?

  1. List(2, 4, 6)
  2. List(1, 2, 3, 1, 2, 3)
  3. 12
  4. List(_ * 2)

What is a closure?

  1. A function with no parameters
  2. A function that uses variables from the scope where it was defined
  3. A method marked final
  4. A lambda that returns Unit