Kotlin List.component3() Function

The Kotlin List.component3() function returns the third element in this list.

Syntax of List.component3()

The syntax of List.component3() function is

list.component3()

Return Value

Kotlin List.component3() function returns third element from the list. If length of the list is less than 3, then the function throws java.lang.IndexOutOfBoundsException.

Example 1: Get Third Element in List

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

Kotlin Program

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

Output

Third element is : "cd"

Example 2: List.component3() with List length < 3

If you call component3() function on list with length less than three, 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", "bc")
    val third = list1.component3()
    print("Third element is : \"$third\"")
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
	at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4350)
	at HelloWorldKt.main(HelloWorld.kt:3)

Conclusion

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