Best Practice for Null Safety In Kotlin

Maraj Hussain
4 min readJul 12, 2019

Kotlin is a very popular language for Android development and was introduced by Google in 2017 for mobile application development. Kotlin is a modern statically typed programming language that will boost your productivity and increase your developer happiness.
As we know that in java the major problem is NullPointerException (NPE) which is very difficult to handle or avoid. But in kotlin, you can deal with this very easily. Here you will learn how to avoid NPEs.

If you haven’t implemented exception handling, the application will crash. Kotlin aims at being a safer language. By default, variables are non-null references and cannot be set to null.

You will learn the following point

  • Differentiate between nullable references and non-nullable references.
  • Safe Call Operator: ?.
  • Asserting Not null Operator: !!
  • Elvis Operator: ?:

Differentiate between nullable references and non-nullable references.

By default in kotlin, all the references are non-nullable and if you want to support nullability, That means you have the ability to declare whether a variable can hold a null value or not. With the feature of nullability in kotlin, the compiler can detect possible NullPointerException at compile time and reduce the possibility of having them thrown at runtime.

In the below code you can see the non-nullable variable which can’t hold a null value

var myString: String = "Kotlin"
myString = null // Compilation Error

You will get compile time error if you want to set the reference as null

If you want to assign a null value to a variable reference in the kotlin then you have to use ? operator like below

var myString: String? = "Kotlin"
myString = null // Compilation Success

You can also use ? operator in class typecasting so with the help of this you will never get a ClassCastException exception like below

onItemClickListener = context as? OnItemClickListener

Here, you only assign onItemClickListener to context as long as the cast to OnItemClickListener succeeds.

Safe Call Operator: ?.

Nullability is very simple but too verbose to use, So kotlin provides the safe call operator ?. it returns the value of a variable if the variable is not null otherwise it will return the null.

var myString: String? = "Kotlin"
print("length is ${myString?.length}")//print the length of the variable
myString = null
print("length is ${myString?.length}")//print the null

in the same case for null check with the safe call operator

if(myString!=null)
print("length is ${myString.length}")
else
null

you can see the difference that Safe Call Operator ?. save the number of lines in the code.

In the above scenario, you will get printed null if the variable is null. If you want to display nothing in the case of the null variable then you must have to use the let with the nullable variable.

var myString: String? = "Kotlin"
print("length is ${myString?.length}")//print the length of the variable
myString = null
myString.let{
print("length is ${myString?.length}")
}

In let you can add the number of the statement as much you want and they will execute when a variable will not null.

You can also use this operator in chain call as if there is an Employee under a department with address (city, state, etc.) and you want to access the city of an employee.

val currentCity: String? = employee?.department?.address?.city

Asserting Not null Operator: !!

As you know how to handle NPEs in kotlin. Now the time is when you want to get an exception if the value is null. Asserting not null operator !! is used when you are sure about the value will never be a null but anyhow if the value becomes null then throw the NullPointerException.

var myString: String? = "Kotlin"
print("length is ${myString!!.length}")//print the length of the variable
myString = null
print("length is ${myString!!.length}")//Through a NPE

Elvis Operator: ?:

If you want to get some default value in case of the null value of a variable. For that Kotlin provide an operator called Elvis Operator which also helps in reducing the code lines.
If you have worked with collection classes like ArrayList and you want to get the size of that. sometimes it gives you the NPE if the ArrayList doesn't initialize yet.

var myString: String? = "Kotlin"
var length = myString?.length ?: -1
print("length is $length")//will print the length of myString variable
myString = null
var length = myString?.length ?: -1
print("length is $length")//will print -1

In the above example, you can see that the elvis operator will work if the left-hand side value is null otherwise it will return to the length of the variable.

Conclusion

We learned what is null safety and how to deal with this in the best way. We learned about the nullable references and non-nullable references, Safe Call Operator, LET, Asserting Not null Operator and Elvis Operator. And it’s easy to deal with NPE in kotlin as compared to JAVA.

--

--

Maraj Hussain
Maraj Hussain

No responses yet