Kotlin Array - component2() Function



The Kotlin array component2() function retrieves the second element of the array object. If the array size is less than two, or empty, this function throw an IndexOutOfBoundsException except.

Syntax

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

operator fun <T> List<T>.component2(): 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 first index (i.e 2nd element) of the array using the component2() function.

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

Output

Following is the output −

The value of the second element of the array is: 1

Example 2

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

fun main(args: Array<String>) {
   var array = arrayOf(10, 23.4, 'c', "tutorialspoint.com")
   try {
      // use the component2() function
      val value = array.component2()
      println("The value of the second element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
      println(exception.printStackTrace())
   }
}

Output

Following is the output −

The value of the second element of the array is: 23.4

Example 3

The below example creates an empty array and uses the component2() function to display the value of the first index (i.e second element) of an array −

fun main(args: Array<String>) {
   var array = emptyArray<String>()
   try {
      val value = array.component2()
      println("The value of the second element of the array is: $value")
   } catch (exception : Exception) {
      println("An element passing the given predicate does not exist or the array is empty")
      println(exception.printStackTrace())
   }
}

Output

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

An element passing the given predicate does not exist or the array is empty
kotlin_arrays.htm
Advertisements