Kotlin: How to understand the not-null assertion operator (!!)

The Kotlin “not-null assertion operator” is expressed as two exclamation points. !! that appear at the end of a variable name. For example: myVariable!!

Here is what the Kotlin documentation says about this operator:

Here is what I learned about the not-null assertion operator after a little bit of experimentation:

The difference between b and b!!:

fun main() {
    val b = null
    val n = b
    println("n $n")
    val l = b!!
    println("l $l")


n null
Exception in thread "main" kotlin.KotlinNullPointerException
 at FileKt.main (File.kt:12) 
 at FileKt.main (File.kt:-1) 

b will print null
b!! will yield an NPE, as seen above.

So the takeaway is:

The non-null assertion operator can be used when we want to force a Null Pointer Exception when accessing a null variable.

For more information about this and other Kotlin “null safety” operators, see: