【发布时间】:2018-02-27 10:23:20
【问题描述】:
fun checkLengthA(str : String?): Int = if (str.isNullOrBlank()) 0 else str.length
“String 类型的可空接收器只允许安全 (?.) 或非空断言 (!!.) 调用?
所有空对象(或空)都被 isNullOrBlank() 捕获,因此 str.length 中的 str 对象永远不能为空(或空)。这可以通过用显式检查替换扩展函数来实现。
fun checkLengthB(str : String?): Int = if (str == null) 0 else str.length
或更简洁的表达方式:
fun checkLengthC(str : String?): Int = str?.length ?: 0
checkLengthB 和 checkLengthC 都可以正常运行。
让我们从 checkLengthA 中删除可空类型以避免编译错误,上面突出显示:
fun checkLengthA(str : String): Int = if (str.isNullOrBlank()) 0 else str.length
现在,我们只允许解析使用字符串类型的非空参数,所以如果我们期望一些空类型,那么我们必须把“?”返回。
看起来编译器不理解 String 类型的 str 在运行 str.length 和扩展函数时永远不会评估为 null,但如果我们在 if-else 中使用 (str == null) 它将毫无问题地编译声明。
谁能解释为什么会这样?
【问题讨论】:
标签: kotlin