Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
What is the Kotlin double-bang (!!) operator?
In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL. In the following example, we will see how to use this double-bang operator.
Example 1
In this example, we will consider a variable "name" and as a programmer, we want to throw a NULL pointer exception whenever the value of "name" is NULL. Now, execute the following code
fun main(args: Array<String>) {
var name: String?
name = null
println(name)
}
Output
It will generate the following output −
null
This code is not actually solving our requirement statement. We wanted to throw a NULL pointer exception whenever the value of "name" is NULL. Let’s modify our previous example with the help of double-bang operator (!!).
Example 2
fun main(args: Array<String>) {
var name: String?
name = null
// Nothing has been used to resolve overload ambiguity exception
println(name!! is Nothing?)
}
Output
It will throw a NULL Pointer Exception at runtime −
Exception in thread "main" java.lang.NullPointerException at MainKt.main(main.kt:6)
