Kotlin Array - component5() Function



The Kotlin array component5() function retrieves the 5th element, or value of the 4rd index of an array object. If the array size is less than five, or empty, this function throw an IndexOutOfBoundsException except.

Syntax

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

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

Parameters

This function does not accepts any parameters

Return value

This function returns an array element of any data type.

Example 1

In this example, lets see how to determine the value of the 4th index (i.e 5th element) of an array using the component5() function.

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

Output

Following is the output −

The 5th element of the array is: 4

Example 2

Now, let's see another example, here we creates an array that stores different type of data. We then use the component5() function to get the 5th element −

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

Output

Following is the output −

The value of the 4th index of the array is: tutorix

Example 3

This example creates an array of size 4 and uses the component5() function to display the value of the 5th element (i.e. 4th index) of an array −

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

Output

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

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