How to Use let with Null Check in Kotlin
In Kotlin, you can use
let with a null check by calling it on a nullable variable using the safe call operator ?.. This runs the let block only if the variable is not null, allowing safe access to the non-null value inside the block.Syntax
The syntax uses the safe call operator ?. followed by let. Inside the let block, the variable is non-null and accessible as it or a named parameter.
nullableVariable?.let { nonNullValue -> /* use nonNullValue safely */ }- The block runs only if
nullableVariableis not null.
kotlin
val nullableString: String? = "Hello" nullableString?.let { nonNullString -> println("String length is ${nonNullString.length}") }
Output
String length is 5
Example
This example shows how to use let to print the length of a nullable string only if it is not null.
kotlin
fun main() {
val name: String? = "Kotlin"
name?.let {
println("Name length: ${it.length}")
}
val emptyName: String? = null
emptyName?.let {
println("This won't print because the value is null")
}
}Output
Name length: 6
Common Pitfalls
A common mistake is to call let without the safe call operator ?., which causes the block to run even if the variable is null, leading to a NullPointerException.
Also, using let without handling the null case separately may cause missed logic for null values.
kotlin
val nullableValue: String? = null // Wrong: This will throw an error // nullableValue.let { println(it.length) } // Right: Use safe call operator nullableValue?.let { println(it.length) }
Quick Reference
Use ?.let { } to run code only when a variable is not null. Inside the block, the variable is non-null and safe to use.
variable?.let { /* safe code */ }- runs if variable is not nullvariable.let { }- runs always, can cause errors if variable is null
Key Takeaways
Use the safe call operator ?. before let to run code only when the variable is not null.
Inside the let block, the variable is non-null and accessible as it or a named parameter.
Avoid calling let without ?. on nullable variables to prevent NullPointerException.
let helps write concise and safe null checks in Kotlin.
Use let for executing code blocks only when a value is present.