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.

Daniel Perez-Gomez

Hi there! 👋 I'm an Android developer currently based in New York City. I write mostly about Android development using Kotlin as well as other programming bits. I'm committed to making this complex field fun and accessible to beginners through my guides and tutorials. I'm also driven by the belief in technology's power to enhance lives, which motivates me to develop apps that are both user-friendly and prioritize accessibility, catering to various needs. Additionally, I host a YouTube channel, “Daniel Talks Code”, where I break down complex concepts into easy-to-follow instructions. Join me in my quest to make the world of Android development inclusive and accessible for all!

Previous
Previous

The great power of .with

Next
Next

Use .run to init objects and perform calculations in one go