RBK*_*RBK 5 null android kotlin android-studio kotlin-null-safety
由于Kotlin有非空的断言,我发现了一些有趣的东西......
val myvar: String = null!!
Run Code Online (Sandbox Code Playgroud)
它会崩溃.
但重点是,它不会在编译时检查.
该应用程序将在运行时崩溃.
它不应该抛出编译时错误吗?
!! 在运行时进行评估,它只是一个运算符.
表达方式 (x!!)
KotlinNullPointerExceptionif x == null,x强制转换返回到相应的非可空类型(例如,它将其作为String在具有类型的变量上调用时返回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
}
Run Code Online (Sandbox Code Playgroud)
这样做x!!会给你相同的结果x.toNonNullable().
| 归档时间: |
|
| 查看次数: |
931 次 |
| 最近记录: |