【发布时间】:2018-08-21 05:45:50
【问题描述】:
这个 kotlin 代码:
fun badKotlin(text: String?): Boolean {
if (text == null) {
return true
}
var temp = text
if (false) {
temp = Arrays.deepToString(arrayOf(text))
}
return temp.isBlank() // <-- only safe (?.) or non null asserted (!!.) calls
}
无法编译并显示消息:only safe (?.) or non null asserted (!!.) calls are allowed on a nullable receiver of type String?
但是如果我添加else:
fun badKotlin(text: String?): Boolean {
if (text == null) {
return true
}
var temp = text
if (false) {
temp = Arrays.deepToString(arrayOf(text))
} else {
temp = Arrays.deepToString(arrayOf(text))
}
return temp.isBlank()
}
全部编译。那么,为什么类型推断会失败呢?
如果我将 temp 的类型更改为 var temp: String = text,它将成功编译!因此,此外,如果我们像这样更改 temp 的分配:temp = String.format("%s", text) 它也会被编译。
更新:
编译成功:
fun badKotlin(text: String?): Boolean {
if (text == null) {
return true
}
var temp = text
if (false) {
temp = String.format("%s", text)
}
return temp.isBlank() // <-- only safe (?.) or non null asserted (!!.) calls
}
还有这个:
fun badKotlin(text: String?): Boolean {
if (text == null) {
return true
}
var temp: String = text
if (false) {
temp = Arrays.deepToString(arrayOf(text))
}
return temp.isBlank() // <-- only safe (?.) or non null asserted (!!.) calls
}
【问题讨论】:
-
var temp = text意味着temp可以为空,而从未发生过的if(false)块不会使其变为非空。在情况 2 中,Arrays.deepToString(arrayOf(text))始终执行,以使 temp 不为空。 -
是的,但请参阅the comment 来回答
-
我建议改用
isNullOrBlank()方法。 -
var temp: String = text和temp = String.format("%s", text)使temp不为空。因此,您的代码可以编译。var temp: String = text表示temp是String,不是null,取值来自text。var temp: String? = text表示temp是字符串,可以为空,并且取值来自text -
那么,我的问题是为什么
String.format("%s", text)使temp不为空,而Arrays.deepToString(arrayOf(text))使temp可以为空?
标签: kotlin type-inference kotlin-null-safety