Check whether a list is empty in Kotlin
This post will discuss different ways to check whether a list is empty in Kotlin. A list is empty if and only if it contains no elements.
1. Using isEmpty()/isNotEmpty() function
A simple solution to check for an empty list in Kotlin is using the isEmpty() function. Its usage is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val list = listOf<String?>() if (list == null) { println("List is null") } if (list.isEmpty()) { println("List is empty") } else { println("List is not empty or null") } } |
Instead of checking separately if the list is null or empty, you can combine the isEmpty() function with the null check:
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf('A', 'B', 'C') if (list == null || list.isEmpty()) { println("List is either empty or null") } } |
Or, do inverse using the isNotEmpty() function:
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf('A', 'B', 'C') if (list != null && list.isNotEmpty()) { println("List is not empty") } } |
2. Using size property
Another solution is to use the size property or the count() function, both return the number of elements in the collection.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val list = listOf('A', 'B', 'C') if (list != null && list.size > 0) { println("List is not empty") } else { println("List is either empty or null") } } |
That’s all about checking whether a list is empty in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)