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?
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?
!!
在运行时评估,它只是一个运算符。
表达方式(x!!)
KotlinNullPointerException
if 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()
。