Chapter 5. Programming with lambdas
This chapter covers
- Lambda expressions and member references
- Working with collections in a functional style
- Sequences: performing collection operations lazily
- Using Java functional interfaces in Kotlin
- Using lambdas with receivers
Lambda expressions, or simply lambdas, are essentially small chunks of code that can be passed to other functions. With lambdas, you can easily extract common code structures into library functions, and the Kotlin standard library makes heavy use of them. One of the most common uses for lambdas is working with collections, and in this chapter you’ll see many examples of replacing common collection access patterns with lambdas passed to standard library functions. You’ll also see how lambdas can be used with Java libraries—even those that weren’t originally designed with lambdas in mind. Finally, we’ll look at lambdas with receivers—a special kind of lambdas where the body is executed in a different context than the surrounding code.
The introduction of lambdas to Java 8 was one of the longest-awaited changes in the evolution of the language. Why was it such a big deal? In this section, you’ll find out why lambdas are so useful and what the syntax of lambda expressions in Kotlin looks like.