首页 > 解决方案 > 已检查可空性时的 Kotlin 空值检查(!!)

问题描述

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

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

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

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

我知道我可以使用以下块,但我不理解这种行为。

user?.let{
    // Block when user is not null
}?:run{
    // Block when user is null
}

标签: androidkotlin

解决方案


这种行为是有原因的。基本上,这是因为编译器无法确保检查user后的值不会变为空if

此行为仅适用于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
}

推荐阅读