Kotlin Array - get() Function



The Kotlin array get() function retrieves the array element at the specified index position, 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 get() function −

operator fun get(index: Int): T

Parameters

This function accepts a single parameter index. It represent the position of the element that need to returned.

Return value

This function returns the specified type of value for the array, based on the element at the specified index position.

Example 1

The following is a basic example, we create an array of size 10. We then use get() function to display the element of the specified index position −

import java.lang.Exception
fun main(args: Array<String>) {
   var array = Array(10) { i -> i}
   val index = 5
   try {
      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 5 in the array is: 5

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) { init -> 1 }
   val index = 3
   try {
      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 3 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 get() to retrieves 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 = 3
   try {
      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

The above code generate the following output −

The value at the index 3 in the array is: Hi
kotlin_arrays.htm
Advertisements