Null Safety in Kotlin Program

Satheesh Guduri
3 min readSep 7, 2021

--

title

Null means no value, if you are trying to access the variable which does not have any value then you will get null pointer exception. But you can find this exception in runtime not at compile time. Is there any way to fix this null pointer exception at compile time instead of runtime. yes….

var name: String

The above statement tells that name is a variable which is string datatype, but name does not contain any data, in java if you are trying to print this name you will get null pointer exception.

In Kotlin, you can not declare a variable without any default value, you have to insert some value or null.

initialize

Suppose, by default i want to provide the value as null, but it does not allow null values. To Insert null values we have different nullable datatypes like String?, Int?,Double?….etc.

if you are using nullable datatypes, it means you can handle the null pointer exceptions at compile time. How…?

nullable datatype

In the above code, we are trying to print the length of name, but the compiler is not allowing and giving the suggestion at compile time that, you are using nullable datatype so there is a chance you may get the null value. To handle this type issues we have null safety operators.

Null Safety Operators:

1. Safe Call (?.)

safe call

In the 5th line, we are using safe call operator, now the compiler is happy, but you can use this operator if you are ok with null data later you can check the condition with null value and here you won’t get null pointer exception.

2. Safe call with let (?.let)

safe call with let

Here, int the 5th line it is checking for the null value, if it is null it won’t go inside just like if condition.

3. Elvis Operator (?:)

elvis

Sometimes, the situations comes like if you getting null value instead of that you can return some defeault value. In above example if it is null then it returns 0. This is just like ternary operator in java.

4. Non-null assertion operator (!!)

non-null

In the 5th line, we are using !! operator, here the compiler is happy, but we will get the run time exception. Because this operator is only used when you are 100% sure that the variable will not be null then use this operator.

100% sure

Here, i am 100% sure that name can’t be null, then i can use this !! operator.

Finally, One last line — Use nullable datatypes in your code to make your program null safe and robust.

Thanks for reading this article, if you like this article please clap for me.

--

--

Satheesh Guduri
Satheesh Guduri

Written by Satheesh Guduri

Mobile App Developer and Trainer

No responses yet