使用 'is' 运算符时是否需要检查 null
Is it necessary to check null when use 'is' operator
我有一个可以为空的实例。狐狸例子
var str: String? = null
所以我需要检查 str 是否为 String。如果我使用 is 运算符,是否需要检查是否为 null。
第一个选项:
if(str is String) {}
第二个选项:
if(str != null && str is String) {}
请帮我看看哪种方式更好用?
is
运算符是安全的,returns 在您提供空实例的情况下为 false
在某个地方,您必须进行 nullcheck。
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
以避免空值检查。
我有一个可以为空的实例。狐狸例子
var str: String? = null
所以我需要检查 str 是否为 String。如果我使用 is 运算符,是否需要检查是否为 null。 第一个选项:
if(str is String) {}
第二个选项:
if(str != null && str is String) {}
请帮我看看哪种方式更好用?
is
运算符是安全的,returns 在您提供空实例的情况下为 false
在某个地方,您必须进行 nullcheck。 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
以避免空值检查。