Not Null Assertion(!!) Operator in Kotlin
On this page (6sections)
Definition
- This operator converts the type of a boxed variable to not-null type.
- This is represented by ”!!”
- When the asserted variable holds a null value, Null Pointer Exception occurs.
Syntax
//"value" variable is asserted to a not null value.
val variable_name = value!!.length
Not Null Assertion Operator(!!) Example Program
//Not Null Assertion Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
//Declaring boxed String
var name: String? = "Little Drops"
//Printing the length of the asserted value
println("Length of $name is ${name!!.length}")
//Setting null to the name variable
name = null
//This statement will create Null Pointer Exception
println("Length of $name is ${name!!.length}")
}
Sample Output
Length of Little Drops is 12
Exception in thread "main" kotlin.KotlinNullPointerException
at NotNullAssertionOperatorKt.main(NotNullAssertionOperator.kt:20)
How It Works
Here is a step-by-step walkthrough of how the Kotlin program for Not Null Assertion(!!) Operator in Kotlin runs, line by line:
fun main(args: Array<String>) {— defines a function used by the program.var name: String? = "Little Drops"— declares or assigns a value the program uses.println("Length of $name is ${name!!.length}")— writes a line of output shown in the sample output.name = null— declares or assigns a value the program uses.
After running it, compare your console output with the Sample Output above. Try changing the values and re-running the program to see how the result changes — experimenting is the fastest way to understand the logic.
Frequently Asked Questions
What is Not Null Assertion(!!) Operator in Kotlin?
This operator converts the type of a boxed variable to not-null type.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Not Null Assertion(!!) Operator?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.