Using the Scope Functions
Learn about the implementation of scope functions in Kotlin.
We'll cover the following...
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.")
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)}
The same code can be rewritten using the let
scoping function:
clintEastwoodQuotes["Unforgiven"]?.let {println(it)}
One common mistake is forgetting to use the safe navigation operator before let
, because ...