5 Programming with lambdas

 

This chapter covers

  • Using lambda expressions and member references to pass snippets of code and behavior to functions
  • Defining functional interfaces in Kotlin and using Java functional interfaces
  • 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, allowing you to reuse more code and be more expressive while you’re at it. The Kotlin standard library makes heavy use of them. In this chapter, you’ll learn what a lambda is, see examples of some typical use cases for lambda functions, what they look like in Kotlin, and their relationship to member references.

You’ll also see how lambdas are fully interoperable with Java APIs and libraries—even those that weren’t originally designed with lambdas in mind—and how you can use functional interfaces in Kotlin to make code dealing with function types even more expressive. 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 values

 
 

5.1.2 Lambdas and collections

 
 

5.1.3 Syntax for lambda expressions

 

5.1.4 Accessing variables in scope

 

5.1.5 Member references

 
 
 

5.1.6 Bound callable references

 
 

5.2 Using Java functional interfaces: Single Abstract Methods (SAM)

 
 
 
 

5.2.1 Passing a lambda as a parameter to a Java method

 
 
 
 

5.2.2 SAM constructors: explicit conversion of lambdas to functional interfaces

 
 
 

5.3 Defining SAM interfaces in Kotlin: "fun" interfaces

 
 

5.4 Lambdas with receivers: "with", "apply", and "also"

 
 
 

5.4.1 Performing multiple operations on the same object: "with"

 
 
 

5.4.2 Initializing and configuring objects: "apply"

 
 
 

5.4.3 Performing additional actions with an object: "also"

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage