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.
Let function behavior and use cases in 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.
name is not null.val name: String? = "Alice" name?.let { println("Hello, $it!") }
val number = 5 val result = number.let { it * 2 } println(result)
val text = "Kotlin" text.let { val upper = it.uppercase(); println(upper) }
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.
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") }
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.
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.
Practice
let function primarily do when called on an object?Solution
Step 1: Understand the purpose of
Theletletfunction takes the object it is called on and passes it as an argument to a block of code.Step 2: Identify the return value of
The result of the block insideletletis returned as the final value of theletcall.Final Answer:
Executes a block of code with the object as its argument and returns the block's result -> Option BQuick Check:
letruns block and returns result [OK]
- Thinking let creates a new object
- Assuming let deletes the object
- Confusing let with toString conversion
let on a nullable variable name to print it only if it's not null?Solution
Step 1: Recognize nullable safe call usage
To safely callletonly whennameis not null, use the safe call operator?..Step 2: Check syntax correctness
name?.let { println(it) }runs the block only ifnameis not null, printing the value.Final Answer:
name?.let { println(it) } -> Option AQuick Check:
Safe call with let = name?.let { ... } [OK]
- Using let without safe call on nullable variable
- Incorrect syntax like let(name) or let? after variable
- Forgetting the safe call operator
val number = 5
val result = number.let { it * 2 }
println(result)Solution
Step 1: Understand the
The variableletblock executionnumberis 5. Theletblock multipliesit(which is 5) by 2.Step 2: Calculate the result and print
The expressionit * 2evaluates to 10, which is assigned toresultand printed.Final Answer:
10 -> Option AQuick Check:
5 * 2 = 10 [OK]
- Thinking let returns original object
- Confusing it with string output
- Expecting syntax error due to block
let:
val text: String? = null
text.let { println(it.length) }Solution
Step 1: Analyze nullable variable usage
The variabletextis nullable and assignednull. Callingletdirectly runs the block even iftextis null.Step 2: Understand runtime behavior
Inside the block,it.lengthis accessed. Sinceitis null, this causes aNullPointerExceptionat runtime.Final Answer:
NullPointerException at runtime -> Option DQuick Check:
Accessing length on null causes runtime error [OK]
- Assuming let skips block if null without safe call
- Expecting compile error instead of runtime error
- Thinking it prints 'null' string
val numbers: List<Int>? = listOf(1, 2, 3), how can you use let to safely calculate and print the sum only if the list is not null and not empty?Solution
Step 1: Use safe call to handle null list
Sincenumbersis nullable, use?.letto run code only if it's not null.Step 2: Check for empty list inside let block
Inside the block, checkit.isNotEmpty()to ensure the list has elements before summing.Step 3: Print sum only if conditions met
If the list is not empty, print the sum usingprintln(it.sum()).Final Answer:
numbers?.let { if (it.isNotEmpty()) println(it.sum()) } -> Option CQuick Check:
Safe call + empty check + sum print = numbers?.let { if (it.isNotEmpty()) println(it.sum()) } [OK]
- Not using safe call on nullable list
- Skipping empty check causing wrong output
- Using let without safe call causing runtime error
Ready to prove it?
Pass the test and this pattern moves unknown
