Skip to main content

How to check if an ArrayList is empty in Kotlin

How to check if an ArrayList is empty in Kotlin.

Here's a step-by-step tutorial on how to check if an ArrayList is empty in Kotlin:

Step 1: Create an ArrayList

First, let's start by creating an ArrayList in Kotlin. You can create an ArrayList using the ArrayList class or the arrayListOf function. Here's an example:

val list = ArrayList<String>()

Step 2: Check if the ArrayList is empty using the size property

In Kotlin, you can check if an ArrayList is empty by using the size property of the ArrayList. If the size is 0, it means the ArrayList is empty. Here's an example:

if (list.size == 0) {
println("ArrayList is empty")
} else {
println("ArrayList is not empty")
}

Step 3: Check if the ArrayList is empty using the isEmpty() function

Alternatively, you can use the isEmpty() function provided by the ArrayList class to check if the ArrayList is empty. The isEmpty() function returns true if the ArrayList is empty, and false otherwise. Here's an example:

if (list.isEmpty()) {
println("ArrayList is empty")
} else {
println("ArrayList is not empty")
}

Step 4: Check if the ArrayList is empty using the isNullOrEmpty() function In Kotlin, you can also use the isNullOrEmpty() function provided by the Kotlin standard library to check if the ArrayList is empty. The isNullOrEmpty() function returns true if the ArrayList is null or empty, and false otherwise. Here's an example:

if (list.isNullOrEmpty()) {
println("ArrayList is null or empty")
} else {
println("ArrayList is not null or empty")
}

Step 5: Handle null ArrayLists

If you have a nullable ArrayList, you need to handle the case where the ArrayList is null before checking if it is empty. You can use the safe call operator (?.) to check if the ArrayList is null. Here's an example:

val nullableList: ArrayList<String>? = null

if (nullableList?.isEmpty() == true) {
println("ArrayList is null or empty")
} else {
println("ArrayList is not null or empty")
}

That's it! You now know how to check if an ArrayList is empty in Kotlin using multiple approaches.