Kotlin Array - set() Function



The Kotlin array set() function sets the array element at the specified index position to the specified value, or throws an IndexOutOfBoundsException if the index is out of bounds for the array. This function is called using the index operator. For example, value = arr[index].

Syntax

Following is the syntax of Kotlin array set() function −

operator fun set(index: Int, value: T)

Parameters

This function accepts the following parameters

  • index. It represent the position of the element, where the value need to be set.

  • value. It represent the value that needs to be assigned at the given index position.

Return value

This function does not returns any value.

Example 1

The following is a basic example, we create an array of size 5. We then use set() function to change the earlier assigned value of the specified index position −

import java.lang.Exception

fun main(args: Array<String>) {
   var array = Array(5) { i -> i}
   val index = 3
   try {
      array.set(index, 4)
      val value = array.get(index)
      println("The value at the index $index in the array is: $value ")
   } catch (exception : Exception) {
      println("Invalid index entered, size of the array is ${array.size}")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value at the index 3 in the array is: 4

Example 2

Now, let's create another example. In this case, we pass an index value that is beyond the array size, which gets to an IndexOutOfBoundsException −

import java.lang.Exception

fun main(args: Array<String>) {
   var array = Array(2) { i -> 0 }
   val index = 4
   try {
      array.set(index, 10)
      val value = array.get(index)
      println("The value at the index $index in the array is: $value ")
   } catch (exception : Exception) {
      println("Invalid index entered, size of the array is ${array.size}")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

Invalid index entered, size of the array is 2
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 2

Example 3

The below example creates an array of size 10 with different types. Then, it assigns values based on the iteration count. We then use the set()to change the element of the specified index value −

import java.lang.Exception

fun main(args: Array<String>) {
   var array = Array(10) { i ->
      if(i<3) {'c'}
      else if(i<5) {"Hi"}
      else {5}
   }
   val index = 2
   try {
      array.set(index, "tutorialspoint")
      val value = array.get(index)
      println("The value at the index $index in the array is: $value ")
   } catch (exception : Exception) {
      println("Invalid index entered, size of the array is ${array.size}")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value at the index 2 in the array is: tutorialspoint 
kotlin_arrays.htm
Advertisements