Closures
Capturing state.
What is a closure?
A closure is a function that captures variables from the surrounding scope where it was defined. It 'closes over' those variables, keeping access to them even after that scope has returned.
object Main {
def main(args: Array[String]): Unit = {
val factor = 3
val multiply = (x: Int) => x * factor
println(multiply(5))
}
}Capturing a free variable
In x => x * factor, x is a parameter but factor is a free variable taken from the enclosing scope. The function carries a reference to it.
object Main {
def main(args: Array[String]): Unit = {
val greeting = "Hello"
val greet = (name: String) => s"$greeting, $name!"
println(greet("Ann"))
println(greet("Bob"))
}
}