Closures
In functional programming, a closure is a function that has access to variables and parameters defined in outer scopes. It is said that they "close over" these variables, hence the name closure.
Let's consider an example where we wish to load names from a database and filter them to only include those that match some search criteria. We will use our old friend, the filter method:
class Student(val firstName: String, val lastName: String) fun loadStudents(): List = ... // Â load from database fun students(nameToMatch: String): List<Student> { return loadStudents().filter { it.lastName == nameToMatch } }
Note that the function literal passed to the filter
method uses the parameter to the outer function. This parameter is defined in an outer scope to the function, so the function is closing over the parameter.
Closures can access local variables as well:
val counter = AtomicInteger...