Sling Academy
Home/Kotlin/Checking if a Collection is Empty in Kotlin

Checking if a Collection is Empty in Kotlin

Last updated: December 04, 2024

When working with collections in Kotlin, it's often necessary to check if a collection is empty. Whether you're dealing with a List, Set, Map, or any other collection type, Kotlin provides several straightforward mechanisms to verify emptiness. This article will explore these various methods through examples and explain when you might choose one over the others.

Using the isEmpty() Function

The most direct way to check if a collection is empty in Kotlin is to use the isEmpty() function. This method is straightforward and checks if the collection's size is equal to zero.

val numbers = listOf<Int>() 

if (numbers.isEmpty()) {
    println("The collection is empty.")
} else {
    println("The collection is not empty.")
}

The output of the above code snippet will be:

The collection is empty.

The isEmpty() method works with other collection types as well, such as Set and Map.

Using the isNotEmpty() Function

Kotlin also offers the isNotEmpty() method, which returns true if the collection has elements and false otherwise. This function might be more readable in certain contexts where you expect non-empty collections.

val fruits = setOf("Apple", "Banana")

if (fruits.isNotEmpty()) {
    println("The fruit collection has elements.")
} else {
    println("The fruit collection is empty.")
}

As expected, the output will be:

The fruit collection has elements.

Checking Empty Maps

Maps in Kotlin can also be checked for emptiness in the same manner. Simply call isEmpty() on the map instance:

val emptyMap = mapOf<String, Int>()

println("Is the map empty? ${emptyMap.isEmpty()}")

This will output:

Is the map empty? true

Using the size Property

Another, perhaps more traditional way to check if a collection is empty is by using the size property. This approach is less idiomatic in Kotlin but can sometimes be used for clarity purposes.

val numbers = listOf(1, 2, 3)

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

The output here will be:

The list is not empty.

When to Use Each Method

While both isEmpty() and size checks achieve the same result, isEmpty() is generally preferred due to its readability and simplicity, and because it is designed specifically to determine emptiness.

Considerations:

  • Use isEmpty() for clarity and readability, as it clearly communicates your intent.
  • Use isNotEmpty() when you are more concerned with the presence of elements in a collection, enhancing code readability.
  • The size approach can be utilized when integrating with non-Kotlin code or when additional condition logic immediately relies on the size.

By utilizing these methods, you can effectively manage and check collections within your Kotlin code, ensuring that you are handling your data structures appropriately to prevent errors or unwanted behaviors.

Next Article: Creating Arrays in Kotlin: Basics and Use Cases

Previous Article: How to Get the Size or Length of a Collection in Kotlin

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin