【发布时间】:2021-01-18 10:51:53
【问题描述】:
我有一个可以为空的实例。狐狸例子
var str: String? = null
所以我需要检查 str 是否为字符串。如果我使用 is 运算符,是否需要检查 null。 第一个选项:
if(str is String) {}
第二个选项:
if(str != null && str is String) {}
请帮助我使用哪种方式更好?
【问题讨论】:
标签: kotlin typechecking
我有一个可以为空的实例。狐狸例子
var str: String? = null
所以我需要检查 str 是否为字符串。如果我使用 is 运算符,是否需要检查 null。 第一个选项:
if(str is String) {}
第二个选项:
if(str != null && str is String) {}
请帮助我使用哪种方式更好?
【问题讨论】:
标签: kotlin typechecking
is 运算符是安全的,在您提供空实例的情况下返回 false
在某个地方,您必须进行空检查。 Kotlin 提供了许多方法来强制非空:
使用非空类型:
var nonNull : String = ""
var nullable : String? = "" // notice the ?
nullable = null // works fine!
nonNull = null // compiler error
如果您遇到可空类型,您可以使用let {} ?: run {} 构造将其解包并使用不可空类型执行您的代码:
nullable?.let { // use "it" to access the now non-null value
print(it)
} ?: run { // else
print("I am null! Big Sad!")
}
Kotlin 严格区分可空的 T? 和不可空的 T。
尽可能使用T 以避免空检查。
【讨论】:
is 运算符转换为 INSTANCEOF 字节码操作,它也检查 null。在使用 is 之前检查 null 并没有真正的好处。