How to Use let Function in Kotlin: Simple Guide
In Kotlin, the
let function is used to execute a block of code on an object and return the block's result. It is often used for null safety and scoping by calling object.let { }, where it refers to the object inside the block.Syntax
The let function is called on an object and takes a lambda block as its argument. Inside the block, the object is referenced as it by default. The block's last expression is the return value of let.
- object.let { it -> }: Calls
letonobject. - it: The object inside the lambda.
- Return value: The result of the lambda block.
kotlin
val result = obj.let { // 'it' is obj here it.toString() }
Example
This example shows how let helps safely work with nullable variables and perform actions only if the variable is not null.
kotlin
fun main() {
val name: String? = "Alice"
// Use let to print name only if it's not null
name?.let {
println("Hello, $it!")
}
val nullName: String? = null
nullName?.let {
println("This won't print because nullName is null")
}
}Output
Hello, Alice!
Common Pitfalls
One common mistake is using let without safe calls on nullable objects, which can cause a NullPointerException. Also, confusing it with the original object outside the lambda can lead to errors.
Wrong way (may cause error):
kotlin
val name: String? = null name.let { println(it?.length) // Safe call inside lambda to avoid NullPointerException }
Common Pitfalls
kotlin
val name: String? = null name?.let { println(it.length) // Safe call, no error, block skipped }
Quick Reference
- Use
letwith safe calls (?.let) to avoid null errors. itrefers to the object inside the lambda.- Returns the lambda result, useful for chaining.
- Good for scoping variables and avoiding temporary variables.
Key Takeaways
Use
let to run code blocks on an object and return the block's result.Combine
let with safe calls (?.let) to handle nullable objects safely.it inside let refers to the object the function is called on.let helps keep code concise by limiting variable scope and enabling chaining.Avoid calling
let on null without safe calls to prevent errors.