Closures
A closure is a function that remembers the variables around it when it was made, like a lunchbox that still holds what you packed. Even later, it can still use those values.
In this page:
Syntax
var captured = value
val closure = (param: Type) => param + captured // uses captured from the outer scope
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting a closure to copy the value of
factor, when it captures the variable, so avarthat changes later affects it. - Creating closures in a loop over a
varand being surprised that they share the same variable. - Forgetting the return type
Int => IntonmakeMultiplier, so the compiler cannot infer the result clearly.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: