Kotlin Array - component3() Function



The Kotlin array component3() function retrieves the third element (i.e 2nd index) of the array object. If the array size is less than three, or empty, this function throw an IndexOutOfBoundsException except.

Syntax

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

operator fun <T> List<T>.component3(): T

Parameters

This function does not accepts any parameters

Return value

This function returns an array element of any data type.

Example 1

In the below example, lets see how to determine the value of the 2nd index of the array using the component3() function.

fun main(args: Array<String>) {
   var array = Array(10) { i -> i }
   try {
      val value = array.component3()
      println("The value of the third element of the array is: $value")
   } catch (exception : Exception) {
      println("Array length is smaller than three")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value of the third element of the array is: 2

Example 2

Now, let's see another example, here we creates an array that stores different type of data. We then use the component3() function to get the value of the 2nd index (i.e. 3rd element) −

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
   try {
      // use the component3() function
      val value = array.component3()
      println("The value of the 2nd index of the array is: $value")
   } catch (exception : Exception) {
      println("Array length is smaller than three")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value of the 2nd index of the array is: c

Example 3

The below example creates an array of size 2 and uses the component3() function to display the 3rd element of an array −

fun main(args: Array<String>) {
   var array = Array(2) { i -> i }
   try {
      val value = array.component3()
      println("The 3rd element of an array is: $value")
   } catch (exception : Exception) {
      println("Array length is smaller than 3")
      println(exception.printStackTrace())
   }
}

Output

The above code generate the following output. If an exception occurs −

Array length is smaller than 3
java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
kotlin_arrays.htm
Advertisements