Purpose of double exclamation operator (null check)


Kotlin lang comes with null safety feature (safe call, elvis operator). And it comes with double exclamation operator (!!) as well (https://kotlinlang.org/docs/reference/null-safety.html#the–operator).

In time that we try to decompile Kotlin code with the (!!) operator, NPE will be thrown.

val sampleVariable = getStr() as String?

Java (decompiled):
String sampleVariable = getStr();
if (sampleVariable == null) {

From this example, I am not sure what is the purpose of the (!!) operator. Any reasons for this operator?


The !! operator tells the compiler that even though the type is nullable, the programmer is sure that the value will not be null in this particular place, and so the null check should be performed and NPE thrown if null value is found.


In that case, safe operator (?.) can be used. In addition, in IntelliJ IDEA IDE, it suggests us to use the safe operator instead of the (!!) operator to get rid of any warning. That is why I had that question. Why do they create the (!!) operator instead of get rid of it?


The difference is that operator .? has nullable return type and returns null, while operator !! has nonnullable return type and throws NPE. So you use one or the other depending on what behavior you want.


!! basically allows you to write
myFun(foo ?: throw AssertionError("Can't happen, I'm sure foo is not null"))

There is nothing more interesting about it.