Purpose of double exclamation operator (null check)


#1

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.

Kotlin:
val sampleVariable = getStr() as String?
sampleVariable!!.length

Java (decompiled):
String sampleVariable = getStr();
if (sampleVariable == null) {
Intrinsics.throwNpe();
}
sampleVariable.getLength();

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


#2

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.


#3

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?


#4

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.


#5

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

There is nothing more interesting about it.