Kotlin Array.isNullOrEmpty() Function
In Kotlin, the Array.isNullOrEmpty()
function is used to check if an array is either null or empty. It returns true
if the array is null or has no elements, and false
otherwise.
This function is helpful when you want to handle arrays that might be null without explicitly checking for both conditions.
In this tutorial, we’ll explore the syntax of the Array.isNullOrEmpty()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.isNullOrEmpty()
function is as follows:
fun <T> Array<out T>?.isNullOrEmpty(): Boolean
The isNullOrEmpty()
function can be called on arrays of any data type (T
) or on nullable array types.
Examples
1. Checking Array.isNullOrEmpty() when given array is null
In this example, we’ll take an array stringsArray
with null value, and use the isNullOrEmpty()
function to check if given array is either null or empty and print the result.
Kotlin Program
fun main() {
val stringsArray: Array<String>? = null
// Checking if the array is null or empty
if (stringsArray.isNullOrEmpty()) {
print("Array is either null or empty.")
} else {
print("Array is neither null nor empty.")
}
}
Output
Array is either null or empty.
stringsArray.isNullOrEmpty()
returns true, and the if-block executes.
2. Checking Array.isNullOrEmpty() when given array is empty
In this example, we’ll take an empty array in stringsArray
, and use the isNullOrEmpty()
function to check if given array is either null or empty and print the result.
Kotlin Program
fun main() {
val stringsArray = arrayOf<String>()
// Checking if the array is null or empty
if (stringsArray.isNullOrEmpty()) {
print("Array is either null or empty.")
} else {
print("Array is neither null nor empty.")
}
}
Output
Array is either null or empty.
stringsArray.isNullOrEmpty()
returns true, and the if-block executes.
3. Checking Array.isNullOrEmpty() when given array contains some elements
In this example, we’ll take an array in stringsArray
with three elements, and use the isNullOrEmpty()
function to check if given array is either null or empty and print the result.
Kotlin Program
fun main() {
val stringsArray = arrayOf("apple", "banana", "cherry")
// Checking if the array is null or empty
if (stringsArray.isNullOrEmpty()) {
print("Array is either null or empty.")
} else {
print("Array is neither null nor empty.")
}
}
Output
Array is neither null nor empty.
stringsArray.isNullOrEmpty()
returns false, and the else-block executes.
Summary
In this tutorial, we’ve covered the isNullOrEmpty()
function in Kotlin arrays, its syntax, and how to use it to check whether an array is either null or empty.