“let” construct for null safety in Kotlin

Sachin Kumar
2 min readNov 9, 2018

Kotlin has one of the most exciting features which makes programmers like us to adopt this fastest growing programming language “Kotlin” and the feature is: It offers “compile-time null safety” which avoids runtime null pointer exception blowing upon us.

We have a “let” construct in Kotlin to:

  • Avoid explicit null checks.
  • Allow passing the nullable value to a function which is expecting the non-nullable value.

Let’s suppose we have a class named “Address”:

class Address {

}

In “main” function of Kotlin we are going to instantiate it with null reference:

fun main(args: Array<String>) {

var address: Address? = null

}

Suppose we have another function named perform which accept the reference of “Address” class:

fun perform(address: Address){

print("perform called")
}

Now, if we call perform from “main” function we will get the error like this:

because perform accepts non-nullable type and we are passing the null reference. We can convert it to non-nullable via non-null assertion operator “!!” but it will throw the null pointer exception when we call perform like this:

perform(address!!)

So, to resolve this we have an amazing construct in Kotlin named “let”, which will not allow the perform function to be called if “address” var has the null value assigned.

E.g. in the given code sample below we are trying to call the perform function with the null value assigned to “address” var:

fun main(args: Array<String>) {

var address: Address? = null

address?.let {
perform(address)
}

}

fun perform(address: Address){

print("perform called")
}

The output is blank in this case with no exception because perform didn’t get called, but if we call “let” with a non-null value of “address”:

fun main(args: Array<String>) {

var address: Address? = Address()

address?.let {
perform(address)
}

}

fun perform(address: Address){

print("perform called")
}

Output:

perform called

Hence, we have concluded how important is “let” construct to make our code safe from null pointer exception without explicitly providing the null checks.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Sachin Kumar
Sachin Kumar

Written by Sachin Kumar

Senior Java Backend Dev | Expertise in Java Microservices, Spring Boot Framework & Android apps development.

No responses yet

Write a response