Daniel Talks Code

View Original

The Usefulness of the .let Scope Function

Another multi-use scope function that Kotlin offers is .let. This is probably the one that I’ve used the most so far, however, I wasn’t aware of its other two benefits. Essentially I’ve mostly used it when combined with the safe call operator ”?” to execute code using its non-null values. However, .let can also save you from having to declare additional variables. You are provided the context object as an argument to be accessed with the “it” keyword, and what you get back is the result of the lambda evaluation.

For example, if I received a long string that I wanted to run a set of operations on and later print, I could do something like this.

val characters = "gandalf, gollum, frodo, sam, pippin, merry, aragorn, gimli, legolas"
characters
    .split(",")
    .map { it.trim(' ') }
    .filter { it.startsWith("g") }
    .let { println(it) }
    // [gandalf, gollum, gimli]

Notice that I only declared a single variable called characters and then chained multiple operations on it, including printing it to the console. ✨

Local Scope Variables for Readability

You can also improve code readability by replacing the “it” keyword provided by the .let scope function with something more meaningful.

val travelers = listOf("frodo", "sam", "gollum")
val meal = travelers.contains("sam").let { samIsCooking ->
    if (samIsCooking) "a delicious stew 🥘" else "lembas bread"
}

println("We ate $meal")
// We ate a delicious stew 🥘

Working with the Safe Call Operator ”?”

Lastly, and possibly the most common use case for .let is to execute a block of code after checking that an optional value is not null. Usually the variable will use the safe call operator ”?” in this situation and you can chain the .let scope function afterwards as follows.

val theOneRing: String? = "💍"
theOneRing?.let { println("🧙 Keep $it secret. Keep $it safe") }
// 🧙 Keep 💍 secret. Keep 💍 safe

I hope this shines a light on the many additional uses of the .let scope function. If there’s anything I missed, please leave me a comment below.

See this content in the original post