Collection Size and Empty Check in Kotlin
On this page (12sections)
Introduction
Collection Size and Empty Check is a fundamental concept every Kotlin developer should understand. Collections let you store and transform groups of values. Kotlin separates read-only and mutable views so you can express intent clearly in your APIs.
The size property returns the number of elements. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- The size property returns the number of elements.
- isEmpty() and isNotEmpty() check whether a collection has elements.
- These checks are useful before processing data.
Syntax
if (list.isNotEmpty()) { ... }
Collection Size and Empty Check in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val emptyList = listOf<String>()
val data = listOf("Kotlin")
println("Empty list isEmpty: ${emptyList.isEmpty()}")
println("Data list size: ${data.size}")
}
Sample Output
Empty list isEmpty: true
Data list size: 1
When to use
Use collections when the number of items is dynamic or when you need map/set semantics instead of a plain list.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val emptyList = listOf<String>()assigns or updates a value used later in the program. -
val data = listOf("Kotlin")assigns or updates a value used later in the program. -
The
println("Empty list isEmpty: ${emptyList.isEmpty()}")statement writes a line to the console — this produces part of the sample output below. -
The
println("Data list size: ${data.size}")statement writes a line to the console — this produces part of the sample output below. -
The size property returns the number of elements.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
- Prefer immutable
listOf,setOf,mapOffor data that should not change after creation. - Use
map,filter, andfoldinstead of manual loops when transforming collections. - Pick the smallest collection type that fits — don’t use a List when a Set is semantically correct.
Common Mistakes
- Modifying a list while iterating it — use
filteror iteratorremovecarefully. - Using
mutableListOfwhen an immutable list would suffice, exposing accidental mutation. - Calling
geton a Map without checking key existence — prefergetOrDefaultorgetValue.
Key Points
- The size property returns the number of elements.
- isEmpty() and isNotEmpty() check whether a collection has elements.
- These checks are useful before processing data.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.