...

/

Using the Scope Functions

Using the Scope Functions

Learn about the implementation of scope functions in Kotlin.

Kotlin has the concept of scoping functions, which are available on any object and can replace the need to write repetitive code. Among other benefits, these scoping functions help us simplify single-expression functions. They are considered higher-order functions because each scoping function receives a lambda expression as an argument.

The Let function

We can use the let() function to invoke a function on a nullable object, but only if the object is not null.

Let’s take, as an example, the following map of quotes:

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."
)
A map of clintEastwoodQuotes

Now, let’s fetch a quote from a movie that may not exist in the collection and print it, but only if it’s not null:

val quote = clintEastwoodQuotes["Unforgiven"]
if (quote != null) {
println(quote)
}
Printing a quote from clint eastwood's Unforgiven movie if available

The same code can be rewritten using the let scoping function:

clintEastwoodQuotes["Unforgiven"]?.let {
println(it)
}
Prints a quote from Unforgiven if available

One common mistake is forgetting to use the safe navigation operator before let, because ...