Kotlin Not Null Assertion !! Operator Tutorial

  • Post author:
  • Post category:Kotlin

In this section, we will learn what the not null assertion operator is and how to use it in Kotlin.

What is Not Null Assertion !! Operator in Kotlin?

The Not Null Assertion operator is used to check the value of a nullable type variable to see if it has a null value or actually pointing to a real value.

Now, if the target variable had a value, then this operator will allow the operation to proceed. But if the variable was pointing to a null value, then this operator will throw a NullPointerException instead.

Note that unlike other operators (like safe call) that return a null value if the variable is null, this assertion operator simply throws an exception and if we don’t handle the exception, our program can crash!

In the Kotlin exception handling section we’ve explained how to handle an exception in Kotlin language.

Kotlin Not Null Assertion !! Operator Syntax:

variable!!.memberName

Here, the variable is the one that might have the null value. Now, after the variable, we put two exclamation marks, which is the symbol of the Not Null Assertion operator, and after that, call the target member of the object (if any) that the variable is pointing at.

Example: using the not null assertion operator in Kotlin

class Address{
    var city:String = "LA"
    var state:String = "CA" 
}

class Employee{
    var address:Address? = null
    var firstName:String = "John"
    var lastName:String = "Doe"
}
fun main(){

    var emp:Employee? = null 
    var res = emp!!.firstName

    println(res)
}

Output:

Exception in thread "main" java.lang.NullPointerException

How does not null assertion operator work in Kotlin?

In this example, as you can see, the emp variable has the value null assigned to it and so if we call this variable using the Not Null Assertion operator, we will get the NullPointerException.

And because we didn’t handle this error in this example properly, our program crashed.

More to Read:

Kotlin Exception Handling

Leave a Reply