The types of Null checking operators.

You facing a headache dealing with NullPointerException here you will find the solution.

The types of Null checking operators.

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 an NPE for short.

Let me show you how the Kotlin language handles this case -->

var a:String  = "ABC"  //Regular initialization means non-null by default.
a = null   //Compilation error.

This is a regular String variable but cannot hold a null reference. But you can allow it to be a nullable String by adding a (?) question mark to it.

var a:String? = "ABC"     //Can holds null
a = null

Then you want to assign variable a to another variable.

var b = a.length   //Error the variable `a` can be null.

So, you need to check if it is null or not, in this article, I will explain in detail the types of Null checking operators.

— Null checking operators —

  • Safe call ( ?. )

    What will happen if you try to call a function inside a class like below:

    ( object.method() ) and your object is Null it will throw the NullPointerException.

    So, you will make a check statement to make sure your object is not null before calling the function. But, it will be so easy if you use the safe call operator.

    ( object?.Method() ) → only calls the method if a non-null reference is passed.

  • Elvis ( ?: ) [ null-coalescing operator ]

    You want to assign an object to a newly created one and you aren`t sure it will be null or not.

    So you can do it like → newObject = object ?: createdNewObject()

    → if the passed object does not equal to null assign it to the newObject otherwise create a new object and assign it to newObject .

    → Returns Null or value.

  • Safe cast ( as? )

    You may face ClassCastException if you try to cast an object that is not of the target type.

    Another option is to use the safe cast to avoid this exception and return null if the casting fails.

    val sString = s as? String
    

    If (s) is String then assign it to the variable else assign Null.

  • Not null assertions ( !! )

    Asserts that something is not null or throws NPE if it is null at the line operator is used.

    ( object!!.Method() ) It will throw a NullPointerException if this object is null.

Reference --> Koltin Website

Happy coding :)