Kotlin Array.size

Kotlin Array.size Property

In Kotlin, the Array.size property is used to retrieve the size or the number of elements in an array.

In this tutorial, we’ll explore the usage of the size property in Kotlin arrays and provide examples of how to retrieve the size of an array.

Usage of Array Size Property

The size property is used to get the size of an array, and it can be accessed directly on the array variable. The syntax is as follows:

val arraySize = array.size

where:

PropertyDescription
arraySizeThe variable to store the size of the array.
arrayThe array for which the size is to be determined.
Parameters of Kotlin Array Size Property

Examples for Array.size Property

1. Getting the Size of an Integer Array

In this example, we’ll use the size property to retrieve the size of a given array of integers intArray.

Kotlin Program

fun main() {
    val intArray = intArrayOf(1, 2, 3, 4, 5)

    // Getting the size of the integer array
    val arraySize = intArray.size

    // Printing the array size
    println("Size of Integer Array\n$arraySize")
}

Output

Size of Integer Array
5

2. Checking for an Empty Array using Array.size property

You can use the size property to check whether an array is empty (has zero elements).

Kotlin Program

fun main() {
    val emptyArray = emptyArray<Int>()

    // Checking if the array is empty
    if (emptyArray.size == 0) {
        print("Given array is empty.")
    } else {
        print("Given array is not empty.")
    }
}

Output

Given array is empty.

You can also use Kotlin Array.isEmpty() to check if an array is empty.

Summary

In this tutorial, we’ve covered the Kotlin Array.size property, its usage, and provided examples of how to retrieve the size of an array.