Kotlin Array.set()

Kotlin Array.set() Function

In Kotlin, the Array.set() function is used to update or modify the value at a specified index in an array. It provides a way to change the value of an existing array element based on its position within the array.

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

Syntax

The syntax of the Array.set() function is as follows:

array.set(index, value)

where

Variable/ParameterDescription
arrayThe array in which to update the element.
indexThe position of the element to be updated within the array.
valueThe new value to be set at the specified index.
Parameters of Kotlin Array set() Function

Examples for Array.set() Function

1. Updating Elements in an Integer Array

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

Kotlin Program

fun main() {
    val intArray = intArrayOf(10, 20, 30, 40, 50)
    println("Original Array\n${intArray.contentToString()}")

    // Updating element at index=2 with 35 using set() function
    intArray.set(2, 35524)

    // Printing the updated array
    println("Updated Array\n${intArray.contentToString()}")
}

Output

Original Array
[10, 20, 30, 40, 50]
Updated Array
[10, 20, 35524, 40, 50]

2. Updating Elements in a String Array

In this example, we’ll use the set() function to update elements in an array of strings.

Kotlin Program

fun main() {
    val stringArray = arrayOf("apple", "banana", "orange", "grape")
    println("Original Array\n${stringArray.contentToString()}")

    // Updating element at index=2 with "mango" using set() function
    stringArray.set(2, "mango")

    // Printing the updated array
    println("Updated Array\n${stringArray.contentToString()}")
}

Output

Original Array
[apple, banana, orange, grape]
Updated Array
[apple, banana, mango, grape]

Summary

In this tutorial, we’ve covered the set() function in Kotlin arrays, its syntax, and how to use it to update array elements. Whether you’re working with arrays of integers, strings, or any other data type, the set() function provides a convenient way to modify the values stored at specific positions within the array.