Get length or size of an Array in Kotlin
To get the length or size of an Array in Kotlin, you can use Array.size
property.
Array.size is a read-only property that returns the number of the elements in the Array.
The syntax to get the length or size of an Array arr
is
arr.size
Examples
Get length of fruitNames Array
In the following program, we take an Arrays of strings: fruitNames
. We use Array.size
property to get the length of this Array.
Kotlin Program
fun main(args: Array<String>) {
val fruitNames = arrayOf("apple", "banana", "cherry")
val length = fruitNames.size
println(length)
}
Output
3
There are three elements in the given Array.
Get length of an empty Array
In the following program, we take an empty Array and try to find its length. Since the Array is empty, size property must return 0. Let us check.
Kotlin Program
fun main(args: Array<String>) {
val fruitNames = arrayOf<String>()
val length = fruitNames.size
println(length)
}
Output
0