Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin non-null assertion on null

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?

like image 552
RBK Avatar asked Jun 27 '17 15:06

RBK


1 Answers

!! is evaluated at runtime, it's just an operator.

The expression (x!!)

  • throws a KotlinNullPointerException if x == null,
  • otherwise, it returns 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().

like image 150
zsmb13 Avatar answered Sep 18 '22 02:09

zsmb13