Using Standard Library Functions

Table 9.1 summarizes the Kotlin standard library functions discussed in this chapter:

Table 9.1  Standard functions

Function Passes receiver to lambda as argument? Provides relative scoping? Returns
let Yes No Lambda result
apply No Yes Receiver
run a No Yes Lambda result
with b No Yes Lambda result
also Yes No Receiver
takeIf Yes No Nullable version of receiver
takeUnless Yes No Nullable version of receiver

a The non-receiver version of run (less commonly used) passes no receiver, performs no relative scoping, and returns the lambda result.

b with is not called on the receiver like this: "hello.with {..}". Instead, it treats the first argument as the receiver, the second being the lambda, like this: with("hello"){..}. It is the only standard function that works this way, which is why we recommend avoiding it.

In this chapter, you saw how to simplify your code using standard functions. They give you the ability to write code that is not only concise but also has the unique feel of Kotlin. We will use standard functions in the rest of this book where applicable.

In Chapter 2, you saw how to represent data using variables. In the next chapter, you will learn how to represent series of data with variables of Kotlin’s List and Set collection types.