Kotlin – Set Element of Array at Specific Index
To set an element of Array with a new value at specified index in Kotlin language, use Array.set() method. Call set() method on this array and pass the index and new value as arguments.
Syntax
The syntax to call set() method on Array arr
with index I
and new value value
passed as argument is
arr.set(i, value)
Examples
In the following program, we take an array of strings, and set the element at index 2
with new value "guava"
using Array.set() method.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry", "mango")
arr.set(2, "guava")
arr.forEach {
println(it)
}
}
Output
apple
banana
guava
mango
If the index specified is out of bounds for the given array, then set() throws ArrayIndexOutOfBoundsException.
In the following program, we take an array of strings, and set the element at index 5
of the array arr
. Since arr is only of size 4, set() throws ArrayIndexOutOfBoundsException.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry", "mango")
arr.set(5, "guava")
arr.forEach {
println(it)
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
at MainKt.main(Main.kt:3)
Conclusion
In this Kotlin Tutorial, we learned how to set element of an Array with new value at specified index, using Array.set() method, in Kotlin programming language with examples.