let Function for Null Safety in Kotlin
Introduction
let Function for Null Safety is a fundamental concept every Kotlin developer should understand. Null safety is one of Kotlin’s signature features. It catches null-related bugs at compile time instead of crashing at runtime with a NullPointerException.
The let function executes a block only when the object is not null. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- The let function executes a block only when the object is not null.
- Inside the block, the object is available as it (or a named parameter).
- It is commonly used with the safe call operator ?.
Syntax
nullableValue?.let { value ->
// use value safely
}let Function for Null Safety in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
var name: String? = "Kotlin"
name?.let { value ->
println("Length of $value is ${value.length}")
}
name = null
name?.let { value ->
println("This will not print")
}
println("Program completed")
}Sample Output
Length of Kotlin is 6
Program completedWhen to use
Use nullable types when a value may legitimately be absent — optional fields, parsed input, or database lookups that can miss.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
var name: String? = "Kotlin"assigns or updates a value used later in the program. -
name?.let { value ->demonstrates null-safe or type-safe Kotlin syntax in action. -
The
println("Length of $value is ${value.length}")statement writes a line to the console — this produces part of the sample output below. -
name = nullassigns or updates a value used later in the program. -
name?.let { value ->demonstrates null-safe or type-safe Kotlin syntax in action. -
The
println("This will not print")statement writes a line to the console — this produces part of the sample output below. -
The
println("Program completed")statement writes a line to the console — this produces part of the sample output below.
Best Practices
Common Mistakes
Key Points
- The let function executes a block only when the object is not null.
- Inside the block, the object is available as it (or a named parameter).
- It is commonly used with the safe call operator ?.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.