首页 > 解决方案 > 在可空类型的接收器上只允许安全 (?.) 或非空断言 (!!.) 调用

问题描述

问题

我正在检查 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

问题:

标签: kotlin

解决方案


当您组合条件时,它们会从左到右进行评估。所以你必须在调用它之前先检查 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)
}

推荐阅读