Kotlin – Update an element in Array at specific index

Update an Array element at specific index in Kotlin

To update an element in Array at specific index with a new value in Kotlin, you can access the element at specific index using arrayName[index] notation and assign the new value using Assignment operator.

The syntax to update the element at index i in the Array arr with a new value newValue is

arr[i] = newValue

Examples

Update element at index=1 in Array with “mango”

In the following program, we take an Arrays of strings: fruitNames. Then update the value at index=1 in the array with a new value of "mango".

Kotlin Program

fun main(args: Array<String>) {
    var fruitNames = arrayOf("apple", "banana", "cherry")
    fruitNames[1] = "mango"
    println(fruitNames.contentToString())
}

Output

[apple, mango, cherry]