Kotlin List.component4() Function

The Kotlin List.component4() function returns the fourth element in this list.

Syntax of List.component4()

The syntax of List.component4() function is

list.component4()

Return Value

Kotlin List.component4() function returns fourth element from the list. If length of the list is less than 4, then the function throws java.lang.IndexOutOfBoundsException.

ADVERTISEMENT

Example 1: Get Fourth Element in List

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

Kotlin Program

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

Output

Fourth element is : "de"

Example 2: List.component4() with List length < 4

If you call component4() function on list with length less than four, 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", "cd")
    val fourth = list1.component4()
    print("Fourth element is : \"$fourth\"")
}

Output

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