Scope functions
Kotlin’s scoping functions, which are accessible on any object, offer a powerful tool to reduce repetitive code. These functions, functioning as higher-order functions, accept lambda expressions as arguments. In this section, we’ll explore essential scoping functions and demonstrate their application by executing code blocks within the context of specified objects. We’ll use the terms “scope” and “context object” interchangeably to refer to the objects these functions act upon.
let function
The let()
function is useful for operating on nullable objects, executing code only if the object is non-null. Consider the map of quotes introduced in Chapter 1:
val clintEastwoodQuotes = mapOf(
"The Good, The Bad, The Ugly" to "Every gun makes its own tune.",
"A Fistful Of Dollars" to "My mistake: four coffins."
)
To safely fetch and print a quote that might not exist...