Skip to main content

How to find the length of an array in Kotlin

How to find the length of an array in Kotlin.

Here's a step-by-step tutorial on how to find the length of an array in Kotlin:

  1. Create an Array: To find the length of an array, you first need to create an array. An array is a container that can hold a fixed number of elements of the same type. You can create an array in Kotlin using the arrayOf() function. For example, let's create an array of integers:

    val numbers = arrayOf(1, 2, 3, 4, 5)
  2. Using the .size property: Kotlin arrays have a built-in property called size that returns the length or size of the array. You can access this property by using the dot (.) operator on the array variable. For example, to find the length of the numbers array created in step 1, you can use the following code:

    val length = numbers.size

    The length variable will now hold the length of the numbers array, which in this case is 5.

  3. Using the .count() function: In addition to the .size property, Kotlin arrays also have a built-in function called count() that can be used to find the length of the array. This function returns the number of elements in the array. Here's an example of how to use the count() function:

    val length = numbers.count()

    Like before, the length variable will now hold the length of the numbers array, which is 5.

  4. Using the .indices property: Another way to find the length of an array is by using the .indices property. The indices property returns a range of valid indices for the array. You can find the length of the array by subtracting the first index from the last index and adding 1. Here's an example:

    val length = numbers.indices.last - numbers.indices.first + 1

    The length variable will now hold the length of the numbers array, which is 5.

  5. Using the .lastIndex property: Kotlin arrays also have a property called lastIndex that returns the index of the last element in the array. To find the length of the array, you can add 1 to the lastIndex property. Here's an example:

    val length = numbers.lastIndex + 1

    The length variable will now hold the length of the numbers array, which is 5.

And that's it! You've learned multiple ways to find the length of an array in Kotlin. You can choose whichever method suits your needs best.