One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. In Java, this would be the equivalent of a NullPointerException or NPE for short. On the other hand, Kotlin by default doesn’t allow any types to have a value of null at compile-time thus saving our apps from the million-dollar mistake called NullPointerException.
In Kotlin there are several null safety operators, some of them are:
- Safe Call Operator ( ?. )
- Elvis Operator ( ?: )
- Not Nulll Assertion ( !! )
- Safe Call with let Operator ( ?.let {..} )
All these operators help us to avoid the NullPointerException and thus make our applications more robust and error-free.
Declaring a null Value
In Kotlin by default, the object is not null. If you want a variable to have a null value, you have to declare it explicitly, And once you do that every time you try to access that variable, Kotlin will throw a compile-time error to avoid NullPointerException unless you check for the null check.
fun main(args: Array<String>){
// val name : String = null -- compile time error
// Nullable Data type
val name: String? = null
}
Now we are going to explore the null safety operators
1. Safe Call
when a variable is set to null you cannot perform actions on that variable or call methods on that variable. The safe call operator allows us to combine a method call and a null check into a single operation.
fun main(){
// Nullable Data type
val name: String? = null
// return the length if 'name' is not null else return NULL
// use it if you don't mind getting null value
println("The length of the string is ${name?.length}")
}
The output of the program will be :
The length of the string is null
Now, what exactly is happening here? so in the runtime when the kotlin compiler found that the value of the variable is null it ignored the length method and simply printed the null value. In case, if the 'name' variable is storing some value then the length of that value will be printed on the console.
fun main(){
// Nullable Data type
val name: String? = "Keshav"
// return the length if 'name' is not null else return NULL
// use it if you don't mind getting null value
println("The length of the string is ${name?.length}")
}
The output of the program will be :
The length of the string is 6
2. Elvis Operator
It provides a default pre-defined value instead of null when used. It is just a shorter way to implement if else condition.
fun main(){
// Nullable Data type
val name: String? = null
val length = if (name != null)
name.length
else
-1
println("Length using if/else ${length}")
// if name is not null then use it
// otherwise use some non-null value
val newlength = name?.length?: -1
println("Length using elvis opreator ${newlength}")
}
The output of the above program is
Length using if/else -1
Length using elvis opreator -1
In case if the value of the name variable is not then instead of -1, the length of the name variable's value will get printed
3. Not Null Assertion
sometimes we need to convert a nullable type to its non-nullable form forcibly. As it turns out, Kotlin’s not-null assertion operator !! does just that and Because we’re sure the value is not null, we can use the !! operator and If we apply this operator on a null value, Kotlin will throw an instance of KotlinNullPointerException.
fun main(){
// Nullable Data type
val name: String? = "keshav"
val lastName: Int? = null
// use it when you are sure the value is not null
// throws NullPointerException if the value is found to be null
println("The length of your name is ${name!!.length}")
println("The length of your last name is ${lastName!!.length}")
}
The output of the above program is
The length of your name is 5
Exception in thread "main" kotlin.KotlinNullPointerException
So before using !! make sure the value is not null. Most of the time, we shouldn’t apply the !! the operator in pure Kotlin code. It’s better to use other and safer options such as null-safe calls or the Elvis operator.
However, while working with some third-party libraries, we may have to use this operator anyway.
4. Safe Call with let Operator
The let function turns an object or variable on which it is called into a parameter of a function usually expressed using a lambda expression. When used with a safe call operator (?.), the code inside the lambda expression be executed only if the parameter is not null
fun main(){
// Nullable Data type
val name: String? = null
// it executes the block only if name is not null
name?.let{
println("The length of the string is ${name?.length}")
}
println("The code in let block didn't run")
}
The output of the program will be :
The code in let block didn't run
If the value of the name is non-null the code inside the lambda expression will be executed.
In this post I have tried to give an insight into some exciting null safety features provided by Kotlin, I would highly recommend you to explore these and try out on your applications. In the future, I will update this post with some good use cases of null in kotlin android applications.