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.

Download Code

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.

Download Code

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:

Download Code

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 ?:.

Download Code

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.

Download Code

Output:

List is null or empty

 
We can combine this with the safe call and the Elvis operator.

Download Code

Output:

List is null or empty

That’s all about checking for a null or empty list in Kotlin.