As Kotlin have the non-null assertion, I found some funny stuff...
val myvar: String = null!!
It will crash.
But the point is, it doesn't check at compile time.
The app will crash at runtime.
Shouldn't it throw compile time error?
!!
is evaluated at runtime, it's just an operator.
The expression (x!!)
KotlinNullPointerException
if x == null
,x
cast to the corresponding non-nullable type (for example, it returns it as a String
when called on a variable with type String?
). This, of course, makes null!!
shorthand for throw KotlinNullPointerException()
.
If it helps, you can think of !!
as doing the same as a function like this does:
fun <T> T?.toNonNullable() : T {
if(this == null) {
throw KotlinNullPointerException()
}
return this as T // this would actually get smart cast, but this
// explicit cast demonstrates the point better
}
So doing x!!
would give you the same result as x.toNonNullable()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With