Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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...