android - 已检查可空性时的 Kotlin 空值检查(!!)

标签 android kotlin

我对 Kotlin 及其空值检查警告有疑问。

假设我创建了一个名为“user”的对象,该对象具有一些属性,如姓名、姓氏等。以下代码是一个示例:

if(user != null) {
    val name = user!!.name
    val surname = user.surname
    val phoneNumber = user.phoneNumber
} else 
    // Something else

为什么,即使我检查了用户不为空,Kotlin 还是希望我使用 !!我第一次调用用户?此时它不能为空。

我知道我可以使用以下 block ,但我不理解这种行为。
user?.let{
    // Block when user is not null
}?:run{
    // Block when user is null
}

最佳答案

这种行为是有原因的。基本上是因为编译器无法保证user的值在 if 之后不会变为 null查看。

此行为仅适用于 var user ,不适用于 val user .例如,

val user: User? = null;
if (user != null) {
  // user not null
  val name = user.name // won't show any errors
}
var user: User? = null;
if (user != null) {
  // user might be null
  // Since the value can be changed at any point inside the if block (or from another thread).
  val name = user.name // will show an error
}
let即使对于 var,您也可以确保不变性变量。 let创建一个与原始变量分开的新最终值。
var user: User? = null
user?.let {
  //it == final non null user
  //If you try to access 'user' directly here, it will show error message,
  //since only 'it' is assured to be non null, 'user' is still volatile.
  val name = it.name // won't show any errors
  val surname = user.surname // will show an error
}

关于android - 已检查可空性时的 Kotlin 空值检查(!!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56956432/

相关文章:

android - adb shell 的 BroadcastReceiver 权限

java - 这个for循环有什么问题?

java - 不可变构造函数注入(inject) Kotlin 类的正确方法

junit - 父类(super class)中的@BeforeAll 未执行

android - LiveData 观察者与 onPrepareOptionsMenu 竞赛

android - 自定义 ArrayAdapter onLongClickListener

android - 恢复 Top Activity 而不是启动 Launcher Activity

android - 使用游标在sqlite中检索具有列值的列名

android - 如何以编程方式将 Android 屏幕/应用程序镜像到屏幕?

kotlin - 限制 Kotlin 中伴随对象的类型