kotlin

Get Length of an Array in Kotlin

The arrays are mutable collections of elements used in the Kotlin programming language. If you want to get the length of an array in Kotlin, you can use Array.size

val employees = arrayOf("John", "Jacob", "Martha", "Neel")
    
val result = employees.size

println( result )

Output

4

In the above code example, we have created a Kotlin Array - employees and want to get the length of the array. We are using Array.size to calculate the length of the array. This will return the number of items that an array contains. It is applicable to all the Array created using Kotlin.

Syntax

Array.size

Check empty array using Array.size

We can also use Array.size to check if an array contains at least one item or not. If Array.size returns 0 then the array is empty and if it is greater than 0 then the array is not empty.

val employees = arrayOf("John", "Jacob", "Martha", "Neel")
    
if (employees.size > 0) {
    println("Array is not empty")
} else {
    println("Array is empty")
}

Output

Array is not empty

In the above code example, we have created an array - of employees and by using employees.size we are checking if the given array is empty or not

Empty array code example

val arr = arrayOf<String>()

if (arr.size > 0) {
    println("Array is not empty")
} else {
    println("Array is empty")
}

Output

Array is empty
Was this helpful?