1
votes

Problem

I'm checking for null, but receiving this error:

// 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)
}

Compilation output:

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

Questions:

  • Why is the compiler complaining?
  • Does the order of if-statement operands matter?
2

2 Answers

2
votes

When you combine conditionals, they are evaluated from left to right. So you have to check for null first before calling isEmpty() on it:

fun isNullOrEmpty(list: List<Int>?): Boolean {
  if (list == null || list.isEmpty()) {
    return true
  }else {
    return false
  } 
}

Note, the if-statement is redundant. Just do this:

fun isNullOrEmpty(list: List<Int>?): Boolean {
  return list == null || list.isEmpty()
}

I changed your function name because it was inconsistent with what you're checking.

Also, there already is a built-in function you can call on nullable lists:

fun main(args: Array<String>) {
  val list: List<Any>? = null
  val test1: Boolean = list.isNullOrEmpty()
  println(test1)
}
0
votes

I'm checking for null. Why is the compiler complaining?

Answer

you call isEmpty() on something that could be null. You must check whether it's null before you call a function on an object. Kotlin does this to avoid NullPointerExceptions

// testNullCheck.kt
fun isNullOrEmpty(list: List<Int>?): Boolean {
  if (list == null || list.isEmpty()) {
    return true
  }else {
    return false
  } 
}

fun main(args: Array<String>) {
  val test: Boolean = isNullOrEmpty(
    listOf<Int>()
  )
  println(test)
}

Compilation output:

leetcode/kotlin [master●] » kotlinr testNullCheck.kt
Compiling, please wait...
true