Kotlin – Check if Array is Empty

Check if Array is Empty in Kotlin

To check if given Array is empty in Kotlin, you can use Array.isEmpty() function. The function returns a boolean value of true if the Array is empty, or false if the array is not empty.

The syntax of the boolean expression to check if the Array arr is empty is

arr.isEmpty()

Examples

Check if the Array arr is empty

In the following program, we take an empty Array of strings: arr. We use Array.isEmpty() function, to programmatically check if the array arr is empty or not.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf<String>()
    if (arr.isEmpty()) {
        println("The array is empty.")
    } else {
        println("The array is not empty.")
    }
}

Output

The array is empty.

Check the output of isEmpty() with an Array of three elements

In the following program, we take an Arrays of strings: arr with three elements in it, and programmatically check if the Array is empty. Since, we have taken a non-empty Array, isEmpty() returns false, and else block runs.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry")
    if (arr.isEmpty()) {
        println("The array is empty.")
    } else {
        println("The array is not empty.")
    }
}

Output

The array is not empty.