Introduction
We check if a collection has items or is empty to decide what to do next in our program.
collection.isEmpty()
collection.isNotEmpty()
collection.size
collection.count()isEmpty() to check if the collection has no elements.isNotEmpty() to check if the collection has one or more elements.val list = listOf(1, 2, 3) println(list.isEmpty()) // false println(list.isNotEmpty()) // true
val emptyList = emptyList<String>() println(emptyList.isEmpty()) // true println(emptyList.isNotEmpty()) // false
val fruits = listOf("apple", "banana", "cherry") println(fruits.size) // 3 println(fruits.count()) // 3
fun main() { val numbers = listOf(10, 20, 30) if (numbers.isNotEmpty()) { println("The list has ${numbers.size} items.") } else { println("The list is empty.") } }
isEmpty() and isNotEmpty() is clearer and safer than comparing size to zero.size and count() return the number of elements; size is usually faster.isEmpty() to check if a collection has no elements.isNotEmpty() to check if it has one or more elements.size or count() to find how many items are in the collection.isEmpty()isNotEmpty() checks for one or more elements, count() and size return the number of elements but do not return a boolean.isEmpty() -> Option DisEmpty() = true [OK]isEmpty() to check for no elements [OK]isEmpty() with isNotEmpty()count() to check emptinesssize() as a function instead of propertyitems is not empty in Kotlin?isNotEmpty() is a function and requires parentheses.isEmpty without parentheses is invalid, size is a property, not a function, so size() is wrong, and count is a function, so count > 0 is invalid.isNotEmpty() with parentheses [OK]isNotEmpty() needs parentheses [OK]size as a functioncount without parenthesesval numbers = listOf(1, 2, 3, 4) println(numbers.size) println(numbers.isEmpty()) println(numbers.isNotEmpty())
numbers.size returns 4.numbers.isEmpty() returns false because the list is not empty.numbers.isNotEmpty() returns true because the list has elements.val data = listOf<String>()
if (data.isEmpty) {
println("No data")
}isEmpty is a function and must be called with parentheses: isEmpty().listOf<String>() creates an empty list correctly, println syntax is correct, and mutability is not required for checking emptiness.users.size > 0 correctly checks if the list has one or more elements.isEmpty() checks for empty, so if (users.isEmpty()) println("Online users: ${users.size}") prints when empty, which is wrong.count is a function, so count == 0 is invalid.isNotEmpty without parentheses is incorrect syntax.Pass the test and this pattern moves unknown