Closures and Lexical Scoping
We'll cover the following...
Functional programmers talk about lambdas and closures. Many programmers use those two terms interchangeably, which is acceptable, as long as we know the difference and can discern which one we’re using based on the context. Let’s take a closer look at how lambdas bind to variables and how that relates to the concept of closures.
Understanding closures and lexical scoping
A lambda is stateless; the output depends on the values of the input parameters. For example, the output of the following lambda is twice the value of the given parameter:
// closures.kts
val doubleIt = { e: Int -> e * 2 }
Sometimes we want to depend on external state. Such a lambda is called a closure—that’s because it closes over the defining scope to bind to the properties and methods that aren’t local. Let’s turn ...