January 2017
Intermediate to advanced
420 pages
9h 25m
English
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 ...
Read now
Unlock full access