Closures

A closure is a function that uses a name from outside itself. The compiler keeps that name alive for as long as the function does, so a function can outlive the method that created it and still see the value it closed over. It is the feature that makes a counter, a configuration and a callback one line each.

A value that outlives its method

counter declares a var and returns a function that changes it. The var belongs to that call, not to the method, so two counters count separately, and the one returned first keeps counting while the other starts at zero:

closures.scala

def counter(start: Int): () => Int = var count = start () => count += 1 count @main def closures(): Unit = val next = counter(10) println(next()) println(next()) val other = counter(0) println(other()) println(next())

scala-cli run --server=false closures.scala

11
12
1
13

The function returned by counter(10) closes over the count of that call; counter(0) creates a second one. The type () => Int says that the function takes no argument and returns an Int, and the empty parentheses are the call.

What a closure captures

A closure over a val cannot change it, and a closure created inside a method sees the parameters of that method as values. Both forms below are pure: the function returned by multiplier multiplies by a factor that no longer exists in any scope, and the greeting is a val of the method body:

capture.scala

def multiplier(factor: Int): Int => Int = n => n * factor @main def capture(): Unit = val triple = multiplier(3) println(triple(5)) println(List(1, 2, 3).map(triple)) val greeting = "Hello" val greet = (name: String) => s"$greeting, $name" println(greet("Ada"))

scala-cli run --server=false capture.scala

15
List(3, 6, 9)
Hello, Ada

triple is a function like any other, so map takes it: a value captured at creation is the cleanest kind of configuration. A closure over a var is the other kind — it has state that a reader cannot see in the type — and a program keeps that state in one place on purpose, as the counter does.

Related

Article author: Arthur Isaev