What is Null Safety Operator?

In kotlin by default the null value is not supported to avoids the null pointer exception we have a lot of null safety operators which helps to avoid the null pointer exception and makes our application more robust and errors. There are four types of null safety operators.

  • Safe call operator(?.)
  • Not null assertion (!!)
  • Elvis operator (?:)
  • safe call with let (?.let{—–})

so how to assign the null value to our variable of name so for that in kotlin we have something called nullable datatype to do that we have to make this string as nullable by using the question mark here so this rectify is our error now similar to string you can create an allowable integer or a nullable float value similarly nullable boolean value and0 even the custom classes such as student or employee so right now I will use the nullable string value now let us try to explode our null safety operators so here these are the comment statements where we will explore all the full types of null safety operators

Safe call operator(?.)

Use it only if you don’t mind getting the null value in the output console. If the variable is null it will simply return null otherwise perform action.

Example
fun main(args: Array<String>) {
	var firstName: String? = "Codinglance"
	var className: String? = null

	println(firstName?.toUpperCase())
	println(firstName?.length)
	println(className?.toUpperCase())
}
Output
COADINGLANCE
12
null

Not null assertion (!!)

Use it when you are two hundred percent sure the value is not null .if string is not null it will show the length in below example but in case if the string is Null then let’s see what happens so in this case the error has occurred and we are getting the exception of the null pointer exception which means that our application has crashed and it is it legal to provide the poor User experience just because our application is no longer running it has been shut down just because of the null value here so always remember you have to use this operator only if you are sure the value is not null.

Example
fun main(args: Array<String>) {
	var str : String? = "Codinglance"
	println(str!!.length)
	str = null
	str!!.length
}
Output
12
Exception in thread "main" kotlin.KotlinNullPointerException
    at FirstappKt.main(firstapp.kt:8)

Elvis operator (?:)

if name is not equal to null then simply find out name taught length else just returned the default value as -1 right now our cool looks very simple with the name is not null simply find out the length of the name is written the default value as -1. it is like a ternary operator in case of Java.

Example
fun main(args: Array<String>) {
	var str : String? = "Coadinglance"
	println(str?.length)
	str = null
	println(str?.length ?: "-1")
	
}
output
12
-1

safe call with let (?.let{—–})

if we have the value as null it does not execute the block as result we will not get any output. So in this way safe call with let avoid null pointer exception and makes your code more safe.

val name: String? = null
name?.let { println(it.toUpperCase()) }

Here, the name variable is not null then lambda expression is executed other wise not.

Nullable and Non-Nullable Types in Kotlin 

The most important advantage of Kotlin that it supports nullability as part of its type System. That means it gives you to declare a variable that can hold a null value or not.By using this in kotlin, the compiler can easily detect possible NullPointerException errors at compile time and help to reduce the possibility of having them thrown at runtime.Kotlin type system is divided into two types of references that is nullable and non-nullable that  can hold nullable references and non-null references respectively.A variable that is of String type can not hold null. If we try to give null to the variable, it gives compiler error.

var s1: String = “hello”
s1 = null // compilation error
To assign a variable null, we can declare a variable as nullable string, written String?
var s2: String? = “hello”
s2 = null // ok
print(s2)

Now, if we need  the length of the string s1, it will not to throw null pointer exception:-

val l = s1.length

But if we need the length of the string s2, the compiler reports an error bcz that would not be safe:-

val l = s2.length// error: variable 's2' can be null

Kotlin program of non-nullable type 

fun main(args: Array<String>){
    // variable is declared as non-nullable
    var s1 : String = "Geeks"
  
    //s1 = null  // gives compiler error
      
    print("The length of string s1 is: "+s1.length)
}

Output:

The length of string s1 is: 5

Here, it will gives compiler time error if we try to assign null to a non-nullable variable then . But, if we try to access the length of the string then it will not through any NullPointerException.

Kotlin program of nullable type

fun main(args: Array<String>) {
    // variable is declared as nullable
    var s2: String? = "GeeksforGeeks" 
    s2 = null    // no compiler error 
    println(s2.length)  // compiler error because string can be null
}

it will give an error. Here, we can easily able to assign null to a nullable type variable. But we must use the safe operator to get the length of the string.

Checking for null in conditions

The most common way used for checking null reference is if-else expression. We can explicitly check that if variable is null or not, and handle the two options differently.

fun main(args: Array<String>) {
    // variable declared as nullable
    var s: String? = “Hello”
    println(s)
    if (s != null) {
        println("String of length ${s.length}")
    } else {
        println("Null string")
    }
    // assign null
    s = null
    println(s)
    if (s != null) {
        println("String of length ${s.length}")
    } else {
        println("Null String")
    }
}

Output:

Hello
String of length 5
null
Null String

Note that we are using if-else block to check the nullability. If string have null then it executes the if block otherwise it executes the else block.

Conclusion

In this article, we explored what is null safety, Koltin’s nullable and non-nullable and null safety features in depth.we discuss how may type are there to solve null pointer in kotlin. We discuss types of references that can hold null values and that cannot hold null values. we discussed about Safe call operator(?.),Not null assertion (!!),Elvis operator (?:),safe call with let (?.let{—–}) and implemented with a an example see the result after compile. we also discuss about nullable type wish example and non-nullable without example and see what is the common way to handle null pointer exception.

You may also like...

0 Comments

No Comment.