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)
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With