0
0
Kotlinprogramming~5 mins

Let function with safe calls in Kotlin

Choose your learning style9 modes available
Introduction

The let function helps you run code only when a value is not null. It keeps your program safe from errors caused by missing values.

When you want to do something only if a variable is not null.
When you want to avoid writing extra checks for null values.
When you want to work with a value inside a small block of code safely.
When you want to chain calls on a variable that might be null.
When you want to keep your code clean and easy to read.
Syntax
Kotlin
variable?.let { nonNullValue ->
    // code using nonNullValue
}

The ?. is a safe call operator that runs let only if variable is not null.

Inside let, the value is not null and can be used safely as nonNullValue.

Examples
This prints a greeting only if name is not null.
Kotlin
val name: String? = "Alice"
name?.let { println("Hello, $it!") }
This does nothing because age is null.
Kotlin
val age: Int? = null
age?.let { println("Age is $it") }
This extracts and prints the email domain if email is not null.
Kotlin
val email: String? = "user@example.com"
email?.let {
    val domain = it.substringAfter("@")
    println("Email domain: $domain")
}
Sample Program

This program prints the user name only if it is not null. It skips printing the city because it is null.

Kotlin
fun main() {
    val userName: String? = "Bob"
    val userCity: String? = null

    userName?.let { println("User name is $it") }
    userCity?.let { println("User city is $it") }
}
OutputSuccess
Important Notes

If the variable is null, the code inside let will not run.

You can use it inside let to refer to the non-null value.

This helps avoid errors called NullPointerException in Kotlin.

Summary

let with safe calls runs code only when a value is not null.

Use ?.let { } to safely work with nullable variables.

This keeps your code safe and clean by avoiding null errors.