Size of an Array in Kotlin

This article will teach you how to use the size property or count() function of the Array class in Kotlin to determine the size of a given array. Examples will be provided.

Kotlin Array Size

To get size of Array in Kotlin, read the size property of this Array object. size property returns number of elements in this Array.

We can also use count() function of the Array class to get the size. We will go through an example to get the size of the Array using count() function.

Arrays are a fundamental part of many programming languages, and Kotlin is no exception. If you’re working with arrays in Kotlin and need to find out how many elements it contains, you can easily get the size of an array using a simple method. In this article, we’ll explore how to obtain the size of an array in Kotlin.

Using the size Property

In Kotlin, arrays come with a built-in property called size that returns the number of elements in the array. This property is accessible directly on the array instance. Let’s take a look at a simple example:

fun main() {
    // Creating an array of integers
    val numbers = intArrayOf(1, 2, 3, 4, 5)

    // Getting the size of the array
    val size = numbers.size

    // Printing the result
    println("The size of the array is: $size")
}

In this example, we first create an array called numbers containing five integers. Then, we use the size property to obtain the size of the array and store it in the variable size. Finally, we print the result.

Dynamically Sized Arrays

It’s important to note that the size property can be used not only with fixed-size arrays but also with dynamically sized arrays. For example:

fun main() {
    // Creating an array of strings
    val names = arrayOf("Alice", "Bob", "Charlie")

    // Getting the size of the array
    val size = names.size

    // Printing the result
    println("The size of the array is: $size")
}

In this case, the names array is dynamically sized, meaning that we don’t specify the size when creating the array. The size property still works seamlessly to retrieve the number of elements in the array.

Conclusion

Obtaining the size of an array in Kotlin is a straightforward process using the size property. Whether you’re working with fixed-size arrays or dynamically sized arrays, the size property provides a convenient way to get the number of elements in the array.

In your Kotlin projects, always remember to leverage the language features to write clean and concise code. The size property is just one example of how Kotlin simplifies common programming tasks.

Related Posts

Creating Byte Arrays in Kotlin

Kotlin – Create String Array

Creating Integer Arrays in Kotlin

Create Empty Array in Kotlin

Creating Arrays in Kotlin

Check Two Strings are Equal in Kotlin

Leave a Reply