Closures
In this page:
Closures
A closure is a function that captures variables from its enclosing scope, continuing to reference them even after that scope has technically finished executing. This lets you build functions that carry their own private, remembered state. Closures are what make patterns like counters or configurable multiplier functions possible without a class.
Note: A closure captures the variable itself, not just its value at creation time -- if the captured var changes later, the closure sees the new value.
Example: Closures
object Main extends App {
def makeMultiplier(factor: Int): Int => Int = {
(x: Int) => x * factor
}
val triple = makeMultiplier(3)
val double = makeMultiplier(2)
println(triple(5))
println(double(5))
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: