Kotlin Array - isNullOrEmpty() Function



The Kotlin array isNullOrEmpty() function is used to check if the array is empty or null. It returns true if the array is either empty or null, and false if the array is not empty.

Syntax

Following is the syntax of Kotlin array isNullOrEmpty() function −

fun Array<*>?.isNullOrEmpty(): Boolean

Parameters

This function does not accepts any parameters.

Return value

This function returns boolean value. true if an array is empty or null. Otherwise; false.

Example 1

Following is the basic example to demonstrate the use of isNullOrEmpty() function to verify array is empty or not −

fun main(args: Array<String>) {
   val array = arrayOf<Int>()
   // check array is empty or not
   val isempty = array.isNullOrEmpty()
   println("$isempty")
}

Output

On execution of the above code we get false because this array is empty −

false

Example 2

The example created an array. We then use isNullOrEmpty function to check an array is null or not −

fun main(args: Array<String>) {
   val nullArray: Array<Any>? = null
   val isnull = nullArray.isNullOrEmpty()
   if(isnull){
      print("Array is null !")
   } else{
      print("Array is not null")
   }    
}

Output

Following is the output −

Array is null !

Example 3

Now, let's see another example. Here, we created an array stores some element. We then use isNullOrEmpty function to check array is empty or not −

fun main(args: Array<String>) {
   val array = arrayOf<String>("tutorialspoint", "India")
   // check array is empty or not
   val empty = array.isNullOrEmpty()
   if(empty == false){
      print("Array is not empty!")
   }else{
      print("Array is empty!")
   }
}

Output

After execution of the above code we get the following output −

Array is not empty!
kotlin_arrays.htm
Advertisements