Using Scope Functions

Table 12.1 summarizes the Kotlin scope functions discussed in this chapter:

Table 12.1  Scope 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, ...

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.