let
- Kotlin course
- Beginner
- Lesson 79/116
- 5 min
Learn null-safe blocks with let.
let for a null-safe block
The ?.let { } combo runs the lambda when the receiver is not null; it does nothing when it is null. Inside the lambda the receiver is known as it and has the non-null type.
val name: String? = "Ava"
name?.let {
println("Hello $it")
}
// Hello AvaThis form says "if not null, do a few things"; it is a short alternative to the if (x != null) block.
it and chained let
Inside ?.let the receiver becomes it automatically, with its non-null type. Multiple let calls can be chained, but nested it hurts readability; an explicit parameter name ({ value -> ... }) is then better.
name?.let { value ->
println("Hello $value")
}Here the name value replaces it; it makes the code more readable.
Practice Greet with let in a null-safe way
Define a val name: String? = "Ava". Print a null-safe greeting with name?.let { println("Hello $it") }.
Starter code
fun main() {
val name: String? = "Ava"
// If name is not null, print a greeting message (use let)
}Sample solution
fun main() {
val name: String? = "Ava"
name?.let { println("Hello $it") }
}Expected output
Hello Ava
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: let block
name?.____ { println(it) }
name?.let { println(it) }
Explanation: name?.let { } runs the lambda when not null.
2 Match expression to role
| Term | Meaning |
|---|---|
?.let { } |
Run when not null |
it |
Single lambda parameter |
name?.length |
Returns null if null |
name ?: "None" |
Default if null |
3 name?.let { println(it) } — what happens if name is null?
- Throws an exception
- Prints println(null)
- Lambda does not run, returns null Correct answer
- it becomes null
Explanation: ?.let does not run the lambda on a null receiver; it returns null.