Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasonable situations to use Kotlin's `let`

Tags:

android

kotlin

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)
like image 492
s1m0nw1 Avatar asked Mar 07 '23 16:03

s1m0nw1


2 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).

like image 144
triad Avatar answered Mar 10 '23 10:03

triad


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)
        }
    }
} 
like image 30
vmtrue Avatar answered Mar 10 '23 11:03

vmtrue