Kotlin Array isEmpty()

Kotlin Array isEmpty()

In Kotlin, the isEmpty() function is used to check whether an array is empty. It returns true if the array has no elements and false otherwise.

In this tutorial, we’ll explore the syntax of the isEmpty() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the isEmpty() function is:

fun <T> Array<out T>.isEmpty(): Boolean

The isEmpty() function returns true if the array has no elements and false otherwise.

Examples for Array isEmpty() function

1. Checking if an Array of Numbers is Empty

In this example, we’ll use isEmpty() to check whether an array of numbers is empty.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 2, 3, 4, 5)

    if ( numbersArray.isEmpty() ) {
        println("The array is empty.")
    } else {
        println("The array is not empty.")
    }
}

Output

The array is not empty.

We have used Array.isEmpty() function as a condition in an if-else statement.

2. Checking if an Empty Array is Empty

In this example, we shall take an empty array and we’ll use isEmpty() to check whether an empty array is empty or not.

Kotlin Program

fun main() {
    val numbersArray = intArrayOf()

    if ( numbersArray.isEmpty() ) {
        println("The array is empty.")
    } else {
        println("The array is not empty.")
    }
}

Output

The array is empty.

Summary

In this tutorial, we’ve covered the isEmpty() function in Kotlin arrays, its syntax, and how to use it to check whether an array is empty. This function is useful for conditionally performing operations based on the presence or absence of elements in an array.