Check for a null or empty list in Kotlin
This article explores different ways to check for a null or empty List in Kotlin. A list is empty if and only if it contains no elements.
1. Using isNullOrEmpty() function
From Kotlin 1.3 onwards, the recommended approach is to use the isNullOrEmpty() function to check for an empty or null list in Kotlin.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { var list: List<String>? = listOf() if (list.isNullOrEmpty()) { println("List is null or empty") } else { println("List contains elements") } } |
Output:
List is null or empty
2. Using orEmpty() with isEmpty() function
Here, the idea is to return an empty list if the given list is null and then use the isEmpty() function to check if the list is empty.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { var list: List<String>? = listOf() if (list.orEmpty().isEmpty()) { println("List is null or empty") } else { println("List contains elements") } } |
Output:
List is null or empty
3. Null check + isEmpty() function
Alternatively, you can precede the isEmpty() function by a null check, as shown below:
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { var list: List<String>? = listOf() if (list == null || list.isEmpty()) { println("List is null or empty") } else { println("List contains elements") } } |
Output:
List is null or empty
Instead of explicitly checking if the list is null, you can use the safe call operator, written as ?. along with the Elvis operator, written as ?:.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { var list: List<String>? = listOf() val isNullOrEmpty = list?.isEmpty() ?: true if (isNullOrEmpty) { println("List is null or empty") } else { println("List contains elements") } } |
Output:
List is null or empty
4. Using count() function
Finally, you can use the count() function, which returns the total number of elements in the collection.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { var list: List<String>? = listOf() if (list == null || list.count() == 0) { println("List is null or empty") } else { println("List contains elements") } } |
Output:
List is null or empty
We can combine this with the safe call and the Elvis operator.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { var list: List<String>? = listOf() if (list?.count() ?: 0 == 0) { println("List is null or empty") } else { println("List contains elements") } } |
Output:
List is null or empty
That’s all about checking for a null or empty list 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 :)