The let function helps you run a block of code on an object safely and clearly. It makes your code easier to read and avoids errors when the object might be null.
0
0
Let function behavior and use cases in Kotlin
Introduction
When you want to do something only if an object is not null.
When you want to limit the scope of a variable to a small block of code.
When you want to transform an object and use the result immediately.
When you want to chain multiple operations on an object in a clean way.
Syntax
Kotlin
object.let { variableName -> // code using variableName }
The object before .let is passed as an argument to the lambda block.
You can name the lambda parameter anything, or omit it and use it by default.
Examples
This prints a greeting only if
name is not null.Kotlin
val name: String? = "Alice" name?.let { println("Hello, $it!") }
This doubles the number and prints 10.
Kotlin
val number = 5 val result = number.let { it * 2 } println(result)
This converts the text to uppercase and prints it.
Kotlin
val text = "Kotlin" text.let { val upper = it.uppercase(); println(upper) }
Sample Program
This program shows two uses of let: one to safely print an email if it exists, and another to double a number and print the result.
Kotlin
fun main() { val email: String? = "user@example.com" // Use let to print email only if it's not null email?.let { println("Sending email to $it") } val number = 10 val doubled = number.let { it * 2 } println("Doubled number is $doubled") }
OutputSuccess
Important Notes
Using let with the safe call operator ?. helps avoid null pointer errors.
The let function returns the result of the last expression inside its block.
You can use let to create temporary variables that don't pollute the outer scope.
Summary
let runs code on an object and returns the block's result.
It is useful for null safety and cleaner code blocks.
Use it to limit variable scope and chain operations.