Kotlin Array.get()

Kotlin Array.get() Function

In Kotlin, the Array.get() function is used to access the element at a specified index in an array. It provides a way to retrieve the value of an array element based on its position within the array.

In this tutorial, we’ll explore the syntax of the get() function, how to use it to access array elements, and provide examples of its usage in Kotlin.

Syntax

The syntax to use the Array.get() function is as follows:

val element = array.get(index)

where:

Variable/ParameterDescription
elementThe variable to store the value of the array element at the specified index.
arrayThe array from which to retrieve the element.
indexThe position of the element to be retrieved within the array.
Parameters of Kotlin Array get() Function

Examples for Array.get() Function

1. Accessing Elements in an Integer Array

In this example, we’ll use the Array.get() function to access elements in a given array of integers intArray.

Kotlin Program

fun main() {
    val intArray = intArrayOf(10, 20, 30, 40, 50)

    // Accessing elements using get() function
    // Get element at index = 2
    val element1 = intArray.get(2)
    // Get element at index = 4
    val element2 = intArray.get(4)

    // Printing the elements
    println("Element at index=2 : $element1")
    println("Element at index=4 : $element2")
}

Output

Element at index=2 : 30
Element at index=4 : 50

Explanation

10, 20, 30, 40, 50   ← given array
 0   1   2   3   4   ← indices

2. Accessing Elements in a String Array

In this example, we’ll use the Array.get() function to access elements in a given array of strings stringArray.

Kotlin Program

fun main() {
    val stringArray = arrayOf("apple", "banana", "orange", "grape")

    // Accessing elements using get() function
    val element1 = stringArray.get(1)
    val element2 = stringArray.get(3)

    // Printing the elements
    println("Element at index 1: $element1")
    println("Element at index 3: $element2")
}

Output

Element at index 1: banana
Element at index 3: grape

Summary

In this tutorial, we’ve covered the get() function in Kotlin arrays, its syntax, and how to use it to access elements at specific indices.