Use let or also to simplify working with nullable objects

suggest change

let in Kotlin creates a local binding from the object it was called upon. Example:

val str = "foo"
str.let {
    println(it) // it
}

This prints foo. Because the lambda’s result is Unit, this let call returns Unit.

The difference between let and also is that let returns the result of the block, while also returns the receiver.

This is useful when you call a function that can return null and you want to run code only when that value is not null:

val str: String? = someFun()
str?.let {
    println(it)
}

This runs the let block only when str is not null. Note the safe-call operator (?.).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents