Skip to main content

Kotlin double exclamation operator

!!

What does the !! operator do?
  • Known by different names such as the double bang or double exclamation or NPE operator.
  • This operator forces the compiler to know a null pointer exception in case a null value is encountered. In such cases, compiler throws a KotlinNullPointerException to be precise.
  • It allows programmers to explicitly ask Kotlin for a NPE.
  • Let us try to understand this by an example
var msg: String?
msg = null
println(msg!!.length)
Here, on line 3, we tell Kotlin compiler to print the value of msg.length if msg is not null; else throw a Kotlin Null pointer exception.
  • The double bang operator is useful when we can't add any meaningful null safely in code, yet code must fail when a null value is encountered.
  • The Kotlin null pointer exception can then be caught and handled accordingly.
  • Although, this should be rarely used given how well Kotlin tries to eliminate NPEs.

Comments