Skip to main content

let Function for Null Safety in Kotlin

3 min read
Share:
On this page (12sections)

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 completed

When 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

  1. The program starts with a main function — the entry point that runs when you execute the file.

  2. var name: String? = "Kotlin" assigns or updates a value used later in the program.

  3. name?.let { value -> demonstrates null-safe or type-safe Kotlin syntax in action.

  4. The println("Length of $value is ${value.length}") statement writes a line to the console — this produces part of the sample output below.

  5. name = null assigns or updates a value used later in the program.

  6. name?.let { value -> demonstrates null-safe or type-safe Kotlin syntax in action.

  7. The println("This will not print") statement writes a line to the console — this produces part of the sample output below.

  8. The println("Program completed") statement writes a line to the console — this produces part of the sample output below.

Best Practices

  • Prefer non-nullable types by default; add ? only when null is a valid state.
  • Use safe call (?.) and Elvis (?:) instead of force unwrap (!!) unless you are certain.
  • Handle nullable collections and nested properties with ?. chains or let blocks.

Common Mistakes

  • Using !! everywhere instead of handling null safely — this reintroduces NPE risk.
  • Forgetting that platform types from Java are implicitly nullable.
  • Comparing nullable strings with == without considering both sides may be null.

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.

Frequently Asked Questions

What is let Function for Null Safety in Kotlin?
The let function executes a block only when the object is not null.
When should I use let Function for Null Safety?
Use nullable types when a value may legitimately be absent — optional fields, parsed input, or database lookups that can miss.
How is let Function for Null Safety different from Java?
It is commonly used with the safe call operator ?.
How do I practice this topic?
Copy the example program into IntelliJ IDEA or Android Studio, run it, then modify values or add print statements to confirm your understanding.

Related Tutorials

Search tutorials