6

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?

4

1 回答 1

11

!!在运行时评估,它只是一个运算符。

表达方式(x!!)

  • 抛出一个KotlinNullPointerExceptionif x == null
  • 否则,它会将强制类型转换返回x到相应的不可为空的类型(例如,String当在类型为 的变量上调用时,它会以 a 的形式返回String?)。

这当然null!!throw KotlinNullPointerException().


如果它有帮助,您可以认为!!与这样的功能相同:

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
}

这样做x!!会给你同样的结果x.toNonNullable()

于 2017-06-27T16:01:56.703 回答