Kotlin List - isEmpty() Function



The Kotlin List isEmpty() function is used to return the boolean value. True if the list is empty means the list does not contain any element. False if the list contains the element.

There are the following use cases of the isEmpty() function:

  • Validation: Before proceeding with a list, make sure it contains elements to avoid errors or unnecessary operations.
  • Conditional Logic: This function executes different code paths depending on whether the list is empty or not.
The isEmpty() function enhances readability, reduces boilerplate code, and improves code safety in various scenarios.

Syntax

Following is the syntax of Kotlin list isEmpty() function −

List.isEmpty()

Parameters

This function does not accepts any parameters.

Return value

This function returns true if the list does not contains any element otherwise returns false.

Example 1

Let's see a basic example of the isEmpty() function, which returns true if the list is empty.

fun main(args: Array<String>) {
   val list = listOf<String>();
   val isEmpty = list.isEmpty();
   if(isEmpty == true){
      println("list is empty!")
   }else{
      println("list is not empty!")
   }
}

Output

Following is the output −

list is empty!

Example 2: Short-Circuit Logic

The following example combines isEmpty() with the other checks to simplify the logic −

fun main(args: Array<String>) {
   val tasks = listOf<String>()

   if (tasks.isEmpty() || tasks.size < 3) {
      println("Not enough tasks to proceed.")
   } else {
      println("Tasks are ready for processing.")
   }
}

Output

Following is the output −

Not enough tasks to proceed.

Example 3

This is another example of isEmpty() function if the list is not empty −

fun main(args: Array<String>) {
   val numbers = listOf(10, 15, 20)
   
   if (numbers.isEmpty()) {
      println("list is empty")
   } else {
      println("list is not empty: " + numbers)
   }
}

Output

Following is the output −

list is not empty: [10, 15, 20]
kotlin_lists.htm
Advertisements