Kotlin Array.isNotEmpty() Function
In Kotlin, the Array.isNotEmpty()
function is used to check if an array is not empty. It returns true
if the array has at least one element and false
if the array is empty.
This function is useful when you want to ensure that an array contains elements before performing operations on it to avoid potential errors such as index out of bounds or division by zero.
In this tutorial, we’ll explore the syntax of the isNotEmpty()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the isNotEmpty()
function is as follows:
fun <T> Array<out T>.isNotEmpty(): Boolean
The isNotEmpty()
function can be called on arrays of any data type (T
).
Examples for Array.isNotEmpty() function
1. Check if given array is not empty using Array.isNotEmpty()
In this example, we’ll use the isNotEmpty()
function to check if an array of integers is not empty and print the result.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 2, 3, 4, 5)
// Checking if the array is not empty
if (numbersArray.isNotEmpty()) {
print("Array is not empty")
} else {
print("Array is empty")
}
}
Output
Array is not empty
Since, given array contains some elements, numbersArray.isNotEmpty()
returns true, and the if block is executed.
Summary
In this tutorial, we’ve covered the isNotEmpty()
function in Kotlin arrays, its syntax, and how to use it to check whether an array is not empty.