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.

5.1. Lambda expressions and member references

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.

5.1.1. Introduction to lambdas: blocks of code as function parameters

5.2. Functional APIs for collections

5.3. Lazy collection operations: sequences

5.4. Using Java functional interfaces

5.5. Lambdas with receivers: “with” and “apply”

5.6. Summary

sitemap