Reasonable situations to use Kotlin's `let`

Viewed 1587

In Kotlin, it's common to use let to execute code if an object (let receiver) isn't null, as an alternative to an if != null check, as in the following:

val nullable: String? = "anything"
nullable?.let {
    println(it)
}

In what other situations does it make sense to make use of let?

FYI, let is part of Kotlin's stdlib and is defined as follows:

@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
4 Answers

I've seen let used to scope nested variables (ignoring let's return):

    some.nested.foo.bar.let { bar -> 
        doSomething(bar)
        doMoreStuff(bar)
    }

It can be nice since it replaces the need to define a local variable, but I'm not sure how useful it actually is.

Could also be done with apply, though the readability is a bit worse, (this instead of bar in the scope).

let is also useful when you work with var variables which are nullable. For instance, we have this code

fun doSomething(value: String) {

}

class A {
    var boo: String? = null
    fun b() {
        if (boo != null) {
            doSomething(boo)
        }
    }
}

There, we have compile-time error inside if block because boo can be changed outside. To fix that we should either create a val variable

class A {
    var boo: String? = null
    fun b() {
        val b = boo
        if (b != null) {
            doSomething(b)
        }
    }
}

or use let

class A {
    var boo: String? = null
    fun b() {
        boo?.let {
            doSomething(it)
        }
    }
} 

you can use let in let in let by naming

someMethodCall()?.let{ nameOne ->
       // ....
       // some code here
       // ....
       val resultCall = nameOne
       someMethod2Call()?.let { -> nameTwo
          // ...
          val myVariable = nameTwo + resultCall
          // ... 
      }
}
Related