Kotlin Array - component4() Function



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

Syntax

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

operator fun <T> List<T>.component4(): 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 3rd index of the array using the component4() function.

fun main(args: Array<String>) {
   var array = Array(10) { i -> i }
   try {
      val value = array.component4()
      println("The 4th 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 4th element of the array is: 3

Example 2

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

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
   try {
      // use the component4() function
      val value = array.component4()
      println("The value of the third 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 third index of the array is: tutorialspoint.com

Example 3

This example creates an array of size 3 and uses the component4() function to display the value of the index 3rd of an array −

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

Output

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

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