Kotlin List.component5() Function

The Kotlin List.component5() function returns the fifth element in this list.

Syntax of List.component5()

The syntax of List.component5() function is

</>
Copy
list.component5()

Return Value

Kotlin List.component5() function returns fifth element from the list. If length of the list is less than 5, then the function throws java.lang.IndexOutOfBoundsException.

Example 1: Get Fifth Element in List

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

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef", "fg", "gh")
    val fifth = list1.component5()
    print("Fifth element is : \"$fifth\"")
}

Output

Fifth element is : "ef"

Example 2: List.component5() with List length < 5

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

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de")
    val fifth = list1.component5()
    print("Fifth element is : \"$fifth\"")
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	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 fifth element of a list, using Kotlin List.component5() function.