Kotlin List.component2() – Examples

Kotlin List.component2()

The Kotlin List.component2() function returns second element from the list.

Syntax

List.component2()

Example 1

In this example,

  1. Take a list with two or more elements.
  2. Call component2() function on the list. The function should return the second element.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a", "b", "c", "d", "e", "f")
    val result = list1.component2()
    print(result)
}

Output

b

Example 2

In this example,

  1. Take a list with less than two elements.
  2. Call component2() function on the list. As there no at least two elements in the list, the function should throw java.lang.ArrayIndexOutOfBoundsException.

Program

fun main(args: Array<String>) {
    val list1 = listOf("a")
    val result = list1.component2()
    print(result)
}

Output

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
	at java.base/java.util.Collections$SingletonList.get(Collections.java:4829)
	at KotlinExampleKt.main(KotlinExample.kt:3)