Syntax error What's the difference between "!!" and "?" in Kotlin?

What's the difference between "!!" and "?" in Kotlin?



In this article, we will take an example and demonstrate the difference between (!!) and (?) in Kotlin.

Example – "!!" and "?" operator in Kotlin

Kotlin provides a wonderful operator to check NULL pointer exceptions. It throws a NULL pointer exception instead of breaking the programming logic whenever the variable is NULL.

In the following example, the value of "test" is NULL. Hence, Kotlin will throw a NULL pointer exception instead of breaking down the logic. The example shows the different uses of "!!" and "?" operators.

fun main(args: Array<String>) {
   val nullValue: String ?=null

   // it will print null
   println("The value is ->"+nullValue?.length)

   // it will throw the exception
   println(nullValue!!.length)
}

Output

On execution, it will produce the following output −

The value is ->null
Exception in thread "main" java.lang.NullPointerException
   at MainKt.main(main.kt:8)

The following table sums up the difference −

Input <<Val>>?.length <<Val>>!!.length
Input is null null Null pointer exception
Updated on: 2022-03-01T10:38:44+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements