Kotlin Let Function : Null Safety and Scoping Example

Home » Kotlin » Kotlin Let Function : Null Safety and Scoping Example

The Kotlin standard library function ‘let’ serves two essential purposes: scoping and null-checks. When invoked on an object, ‘let’ triggers the execution of a specified block of code and yields the result of its final expression. Within this block, the object can be accessed using the reference ‘it’ (by default) or a chosen custom name. Let’s explore the features of Kotlin let function.

The ‘let’ function in Kotlin is a higher-order function that allows you to perform a set of operations on a non-null object within a specific scope. It is particularly useful when dealing with nullable objects, as it ensures that the block of code is executed only when the object is not null.

Kotlin Let Function : Null Safety

One of the primary reasons to use ‘let’ is to handle nullable objects safely. Instead of using multiple null checks, you can chain them with ‘let,’ reducing the verbosity of your code significantly. This ensures that the block of code inside ‘let’ is executed only when the object is not null.

Kotlin Let Function : Null Safety and Scoping Example

fun main()
{
  val bookInfo:String? = "Science Book!"
  bookInfo?.let {
      println(it)
  }
}

Output

Science Book!

fun main()
{
  val bookInfo:String? = null
  bookInfo?.let {
      println(it)
  }
}

The above program will not print anything because the ‘let’ function will never execute until it receives a value. It does not execute on null values.

The ‘let’ function is also beneficial when you need to transform data from one type to another, especially within a chain of method calls. It helps to avoid unnecessary intermediate variables and keeps your code clean and concise.

fun main()
{
 val nullableString: String? = "Hello, Kotlin!"
 val length: Int? = nullableString?.let { it.length }
 println(length)
}

Output

14

In this example, we have a nullable string nullableString with the value “Hello, Kotlin!”. The variable length is declared as an Int? (nullable Int) and is assigned the result of the let function.

The let function is called on nullableString using the safe call operator ?.. This ensures that the block inside let is only executed when nullableString is not null.

Inside the let block, the parameter it refers to the non-null value of nullableString, which is “Hello, Kotlin!”. The length property of this string is accessed using it.length, which will return the length of the string.

Finally, the value of length will be the length of the string “Hello, Kotlin!”, which is 14, because the nullableString is not null. If nullableString had been null, the let block would not have been executed, and length would remain null.

Kotlin let for Scoping

‘let’ can be used to limit the scope of variables and resources. For instance, you can use ‘let’ to execute a block of code on a non-null object and perform cleanup operations once the block finishes execution.

Open Kotlin play ground and write the following program

fun fetchDataFromServer(): String? {
    return "Data received from server"
}

fun main() {
    val result = fetchDataFromServer()

    // Using 'let' to process 'data' and perform cleanup
    result?.let { data ->
        println("Data received: $data")

        println("Cleanup after processing data.")
    }

    // Code outside the 'let' scope
    println("End of program")
}

Data received: Data received from server
Cleanup after processing data.
End of program

The ‘let’ function in Kotlin is a powerful tool that can simplify null safety checks, and perform data transformation efficiently.

You may also like...