我对 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/