Kotlin – Check if List is Empty
To check if a List is empty in Kotlin, call isEmpty()
function on this List object.
The Kotlin List.isEmpty() function checks if the list is empty or not, and returns a boolean value.
Syntax of List.isEmpty()
The syntax of List.isEmpty() function is
</>
Copy
list.isEmpty()
Return Value
List.isEmpty() function returns true if the collection is empty (contains no elements), false otherwise.
Example 1: Check if List is Empty
In this example, we will take an empty list, and check if it is empty or not programmatically.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
val list1 = listOf<String>()
if (list1.isEmpty()) {
print("List is empty.")
} else {
print("List is not empty.")
}
}
Output
List is empty.
Example 2: isEmpty() with Non-empty List
In this example, we will take a list with some elements, and check if the list is empty using isEmpty() function.
Kotlin Program
</>
Copy
fun main(args: Array<String>) {
val list1 = listOf("ab", "bc", "cd", "de")
if (list1.isEmpty()) {
print("List is empty.")
} else {
print("List is not empty.")
}
}
Output
List is not empty.
Conclusion
In this Kotlin Tutorial, we learned how to check if a list is empty or not, using Kotlin List.isEmpty() function.