Kotlin List.component2() Function

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

Syntax of List.component2()

The syntax of List.component2() function is

list.component2()

Return Value

Kotlin List.component2() function returns second element from the list. If length of the list is less than 2, then the function throws java.lang.IndexOutOfBoundsException.

ADVERTISEMENT

Example 1: Get Second Element in List

In this example, we will take a list of elements of string type, and get the second element from this list using List.component2() function.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val second = list1.component2()
    print("Second element is : \"$second\"")
}

Output

Second element is : "bc"

Example 2: List.component2() with List length < 2

If you call component2() function on list with length less than two, then the function throws java.lang.IndexOutOfBoundsException. Let us check with a Kotlin example program.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab")
    val second = list1.component2()
    print("Second element is : \"$second\"")
}

Output

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

Conclusion

In this Kotlin Tutorial, we learned how to get the second element of a list, using Kotlin List.component2() function.