kotlin - 在可空类型的接收器上只允许安全 (?.) 或非空断言 (!!.) 调用
问题描述
问题
我正在检查 null,但收到此错误:
// testNullCheck.kt
fun isNullOrEmpty(list: List<Int>?): Boolean {
if (list.isEmpty() || list == null ) {
return true
}else {
return false
}
}
fun main(args: Array<String>) {
val test: Boolean = isNullOrEmpty(
listOf<Int>()
)
println(test)
}
编译输出:
leetcode/kotlin [master●] » kotlinr testNullCheck.kt
Compiling, please wait...
testNullCheck.kt:2:11: error: only safe (?.) or non-null asserted (fg.) calls are allowed on a nullable receiver of type List<Int>?
if (list.isEmpty() || list == null ) {
^
1
2
问题:
- 为什么编译器会抱怨?
- if 语句操作数的顺序是否重要?
解决方案
当您组合条件时,它们会从左到右进行评估。所以你必须在调用它之前先检查 null isEmpty()
:
fun isNullOrEmpty(list: List<Int>?): Boolean {
if (list == null || list.isEmpty()) {
return true
}else {
return false
}
}
请注意,if 语句是多余的。只需这样做:
fun isNullOrEmpty(list: List<Int>?): Boolean {
return list == null || list.isEmpty()
}
我更改了您的函数名称,因为它与您正在检查的内容不一致。
此外,已经有一个可以在可空列表上调用的内置函数:
fun main(args: Array<String>) {
val list: List<Any>? = null
val test1: Boolean = list.isNullOrEmpty()
println(test1)
}
推荐阅读
- java - Java Applet Pong 游戏 if 语句不停止
- prometheus - 如何重新标记 consul sd 配置以获取基于 consul 元数据的服务发现统计信息?
- html - 如何通过边框内的所有链接和粗体标记段落的某些文本
- hadoop - 使用 Sqoop / 套接字创建错误的 HSQL 到 Hadoop
- node.js - 返回类中的中间件
- swift - 如何在 macOS 上访问 aNotification.userInfo 字典
- django - 更改 django 的默认 md5 salting
- google-data-studio - LEGACY 架构和 Data Studio Apps 脚本服务之间的差异
- java - 具有n级依赖关系的多模块maven spring boot项目
- c++ - QInputDialog 为 getDouble() 显示逗号而不是点