android - 已检查可空性时的 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
}
解决方案
这种行为是有原因的。基本上,这是因为编译器无法确保检查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
}
推荐阅读
- angular - 指令点击外角 6
- java-8 - 使用java 8 Stream按第一个值对字符串数组进行分组
- hl7-fhir - FHIR .NET API 如何支持资源中的未知成员?
- c# - MVC Http PUT 不起作用
- elasticsearch - 基本认证 Kibana REST API
- ant - Jmeter with ant - 报告创建
- javascript - HTML e JAVASCRIPT 表扫描
- ios - 使用具有 Double 的通用闭包函数时 Swift 泄漏
- android - 为什么 logcat 不像 Android Studio 的 Run 视图那样捕获完整的堆栈跟踪?
- c++ - Node-gyp/C++ 导入共享库 (.so)