What is double bang in kotlin :
Double bang (!!) or double exclamation operator or not-null assertion operator is used with variables if you are sure that the value will be always non-null. If a value is null and if we are using not-null assertion operator, it will throw one null pointer exception. So, we should use this operator only if we want to throw one exception always if any null value found.
For example :
fun main(args: Array) {
println("Enter a string : ")
var userInput = readLine()
val inputLength = userInput!!.length
println("Length of the string is : $inputLength")
}
This is a simple program to print out the user input string. If you run the program, it will ask the user to enter a string and then print out the length of the string.
Now, let’s change the program to assign the value of userInput to “null” as below :
fun main(args: Array) {
println("Enter a string : ")
var userInput = readLine()
userInput = null
val inputLength = userInput!!.length
println("Length of the string is : $inputLength")
}
The program will throw one kotlin.KotlinNullPointerException this time.
So, use the double bang operator if you don’t want a specific variable null.
Hope you have found this quick tutorial useful. If you have anything else in mind or if you want to share anything with other readers, drop one comment below.
You might also like :
-
Kotlin tutorial : Character in kotlin and functions of Character class
-
Kotlin program to change uppercase and lowercase of a string
-
[Trim leading whitespace characters using trimMargin in Kotlin
](https://www.codevscolor.com/kotlin-trim-leading-whitespace)